@kollors/deep-json-server 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -31
- package/README.ru.md +31 -31
- package/index.js +2 -3
- package/package.json +1 -1
- package/src/utils.js +3 -0
package/README.md
CHANGED
|
@@ -31,37 +31,6 @@ npm run mock
|
|
|
31
31
|
|
|
32
32
|
The default address is `http://127.0.0.1:4001`. You can also pass `--host` and `--port`, or set the `HOST` and `PORT` environment variables.
|
|
33
33
|
|
|
34
|
-
## OpenAPI generation
|
|
35
|
-
|
|
36
|
-
Create a small configuration file next to the database, for example `mock/database-schema.json`:
|
|
37
|
-
|
|
38
|
-
```json
|
|
39
|
-
{
|
|
40
|
-
"movies": {
|
|
41
|
-
"optional": ["description"],
|
|
42
|
-
"formats": {
|
|
43
|
-
"coverSrc": "uri"
|
|
44
|
-
}
|
|
45
|
-
},
|
|
46
|
-
"users": {
|
|
47
|
-
"formats": {
|
|
48
|
-
"avatarSrc": "uri",
|
|
49
|
-
"bornAt": "date"
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
```
|
|
54
|
-
|
|
55
|
-
Generate an OpenAPI 3.0.3 file and exit:
|
|
56
|
-
|
|
57
|
-
```bash
|
|
58
|
-
deep-json-server mock/database.json --generate mock/database-schema.json mock/openapi-schema.yaml
|
|
59
|
-
```
|
|
60
|
-
|
|
61
|
-
The generator infers resources and field types from all database records. Fields present in every record are required unless listed in `optional`; `formats` adds OpenAPI formats such as `date` and `uri`. Nested fields use dot paths, for example `actors.id`.
|
|
62
|
-
|
|
63
|
-
The generated document describes CRUD endpoints, pagination, sorting, deep filters, `_embed`, and response relations inferred from `...Id` and `...Ids` fields. It can be used as input for tools such as RTK Query OpenAPI Codegen. OpenAPI is generated only when `--generate` is passed; normal server startup does not rewrite the file.
|
|
64
|
-
|
|
65
34
|
## Example database
|
|
66
35
|
|
|
67
36
|
This example is based on a movie catalog. It intentionally has no clothes resource. The genre names are real film genres, while `Gangster film` demonstrates a self-referencing subgenre.
|
|
@@ -226,6 +195,37 @@ Relations are inferred by convention:
|
|
|
226
195
|
|
|
227
196
|
They are soft references: the server resolves them when requested but does not enforce referential integrity when data is written.
|
|
228
197
|
|
|
198
|
+
## OpenAPI generation
|
|
199
|
+
|
|
200
|
+
Create a small configuration file next to the database, for example `mock/database-schema.json`:
|
|
201
|
+
|
|
202
|
+
```json
|
|
203
|
+
{
|
|
204
|
+
"movies": {
|
|
205
|
+
"optional": ["description"],
|
|
206
|
+
"formats": {
|
|
207
|
+
"coverSrc": "uri"
|
|
208
|
+
}
|
|
209
|
+
},
|
|
210
|
+
"users": {
|
|
211
|
+
"formats": {
|
|
212
|
+
"avatarSrc": "uri",
|
|
213
|
+
"bornAt": "date"
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
Generate an OpenAPI 3.0.3 file and exit:
|
|
220
|
+
|
|
221
|
+
```bash
|
|
222
|
+
deep-json-server mock/database.json --generate mock/database-schema.json mock/openapi-schema.yaml
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
The generator infers resources and field types from all database records. Fields present in every record are required unless listed in `optional`; `formats` adds OpenAPI formats such as `date` and `uri`. Nested fields use dot paths, for example `actors.id`.
|
|
226
|
+
|
|
227
|
+
The generated document describes CRUD endpoints, pagination, sorting, deep filters, `_embed`, and response relations inferred from `...Id` and `...Ids` fields. It can be used as input for tools such as RTK Query OpenAPI Codegen. OpenAPI is generated only when `--generate` is passed; normal server startup does not rewrite the file.
|
|
228
|
+
|
|
229
229
|
## Programmatic API
|
|
230
230
|
|
|
231
231
|
```js
|
package/README.ru.md
CHANGED
|
@@ -31,37 +31,6 @@ npm run mock
|
|
|
31
31
|
|
|
32
32
|
По умолчанию сервер доступен по адресу `http://127.0.0.1:4001`. Адрес и порт можно задать через `--host` и `--port` либо переменные окружения `HOST` и `PORT`.
|
|
33
33
|
|
|
34
|
-
## Генерация OpenAPI
|
|
35
|
-
|
|
36
|
-
Создайте рядом с базой небольшой файл конфигурации, например `mock/database-schema.json`:
|
|
37
|
-
|
|
38
|
-
```json
|
|
39
|
-
{
|
|
40
|
-
"movies": {
|
|
41
|
-
"optional": ["description"],
|
|
42
|
-
"formats": {
|
|
43
|
-
"coverSrc": "uri"
|
|
44
|
-
}
|
|
45
|
-
},
|
|
46
|
-
"users": {
|
|
47
|
-
"formats": {
|
|
48
|
-
"avatarSrc": "uri",
|
|
49
|
-
"bornAt": "date"
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
```
|
|
54
|
-
|
|
55
|
-
Сгенерируйте OpenAPI 3.0.3 и завершите работу:
|
|
56
|
-
|
|
57
|
-
```bash
|
|
58
|
-
deep-json-server mock/database.json --generate mock/database-schema.json mock/openapi-schema.yaml
|
|
59
|
-
```
|
|
60
|
-
|
|
61
|
-
Генератор определяет ресурсы и типы полей по всем записям базы. Поля, присутствующие в каждой записи, считаются обязательными, если они не перечислены в `optional`; `formats` добавляет форматы OpenAPI, например `date` и `uri`. Для вложенных полей используются пути через точку, например `actors.id`.
|
|
62
|
-
|
|
63
|
-
В сгенерированном документе описаны CRUD, пагинация, сортировка, глубокие фильтры, `_embed` и связи в ответах, определённые по полям `...Id` и `...Ids`. Файл можно передать, например, в RTK Query OpenAPI Codegen. OpenAPI создаётся только с параметром `--generate`; обычный запуск сервера файл не перезаписывает.
|
|
64
|
-
|
|
65
34
|
## Пример базы данных
|
|
66
35
|
|
|
67
36
|
Пример основан на каталоге фильмов. В нём намеренно нет сущности одежды. Используются реальные жанры фильмов, а `Гангстерский фильм` демонстрирует связь с родительским жанром.
|
|
@@ -226,6 +195,37 @@ GET /countries/1?_embed=users
|
|
|
226
195
|
|
|
227
196
|
Это мягкие ссылки: сервер загружает их по запросу, но не проверяет ссылочную целостность при записи данных.
|
|
228
197
|
|
|
198
|
+
## Генерация OpenAPI
|
|
199
|
+
|
|
200
|
+
Создайте рядом с базой небольшой файл конфигурации, например `mock/database-schema.json`:
|
|
201
|
+
|
|
202
|
+
```json
|
|
203
|
+
{
|
|
204
|
+
"movies": {
|
|
205
|
+
"optional": ["description"],
|
|
206
|
+
"formats": {
|
|
207
|
+
"coverSrc": "uri"
|
|
208
|
+
}
|
|
209
|
+
},
|
|
210
|
+
"users": {
|
|
211
|
+
"formats": {
|
|
212
|
+
"avatarSrc": "uri",
|
|
213
|
+
"bornAt": "date"
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
Сгенерируйте OpenAPI 3.0.3 и завершите работу:
|
|
220
|
+
|
|
221
|
+
```bash
|
|
222
|
+
deep-json-server mock/database.json --generate mock/database-schema.json mock/openapi-schema.yaml
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
Генератор определяет ресурсы и типы полей по всем записям базы. Поля, присутствующие в каждой записи, считаются обязательными, если они не перечислены в `optional`; `formats` добавляет форматы OpenAPI, например `date` и `uri`. Для вложенных полей используются пути через точку, например `actors.id`.
|
|
226
|
+
|
|
227
|
+
В сгенерированном документе описаны CRUD, пагинация, сортировка, глубокие фильтры, `_embed` и связи в ответах, определённые по полям `...Id` и `...Ids`. Файл можно передать, например, в RTK Query OpenAPI Codegen. OpenAPI создаётся только с параметром `--generate`; обычный запуск сервера файл не перезаписывает.
|
|
228
|
+
|
|
229
229
|
## Программный API
|
|
230
230
|
|
|
231
231
|
```js
|
package/index.js
CHANGED
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
import { resolve } from 'node:path';
|
|
4
3
|
import process from 'node:process';
|
|
5
|
-
import { fileURLToPath } from 'node:url';
|
|
6
4
|
import { runCli } from './src/cli.js';
|
|
5
|
+
import { isMainModule } from './src/utils.js';
|
|
7
6
|
|
|
8
7
|
export { createOpenApiDocument, generateOpenApi } from './src/openapi.js';
|
|
9
8
|
export { createServer, startServer } from './src/server.js';
|
|
10
9
|
|
|
11
|
-
if (
|
|
10
|
+
if (isMainModule(process.argv[1], import.meta.url)) {
|
|
12
11
|
await runCli();
|
|
13
12
|
}
|
package/package.json
CHANGED
package/src/utils.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { realpathSync } from 'node:fs';
|
|
1
2
|
import { resolve } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
2
4
|
|
|
3
5
|
const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
4
6
|
|
|
@@ -11,6 +13,7 @@ export const createHttpError = (statusCode, message) => {
|
|
|
11
13
|
};
|
|
12
14
|
|
|
13
15
|
export const getResourceNames = (data) => Object.entries(data).filter(([, value]) => Array.isArray(value)).map(([resource]) => resource);
|
|
16
|
+
export const isMainModule = (filePath, moduleUrl) => filePath != null && realpathSync(resolve(filePath)) === fileURLToPath(moduleUrl);
|
|
14
17
|
export const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
15
18
|
export const isSafeKey = (key) => !UNSAFE_KEYS.has(key);
|
|
16
19
|
export const toArray = (value) => (Array.isArray(value) ? value : [value]);
|