@kollors/deep-json-server 0.1.1 → 0.2.0
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 +36 -2
- package/README.ru.md +36 -2
- package/index.js +3 -579
- package/package.json +6 -4
- package/src/cli.js +70 -0
- package/src/openapi.js +258 -0
- package/src/query.js +233 -0
- package/src/relations.js +116 -0
- package/src/server.js +153 -0
- package/src/utils.js +57 -0
package/README.md
CHANGED
|
@@ -17,7 +17,8 @@ Add a script to `package.json`:
|
|
|
17
17
|
```json
|
|
18
18
|
{
|
|
19
19
|
"scripts": {
|
|
20
|
-
"mock": "deep-json-server mock/database.json --port 4001"
|
|
20
|
+
"mock": "deep-json-server mock/database.json --port 4001",
|
|
21
|
+
"openapi": "deep-json-server mock/database.json --generate mock/database-schema.json mock/openapi-schema.yaml"
|
|
21
22
|
}
|
|
22
23
|
}
|
|
23
24
|
```
|
|
@@ -30,6 +31,37 @@ npm run mock
|
|
|
30
31
|
|
|
31
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.
|
|
32
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
|
+
|
|
33
65
|
## Example database
|
|
34
66
|
|
|
35
67
|
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.
|
|
@@ -197,7 +229,7 @@ They are soft references: the server resolves them when requested but does not e
|
|
|
197
229
|
## Programmatic API
|
|
198
230
|
|
|
199
231
|
```js
|
|
200
|
-
import { createServer, startServer } from '@kollors/deep-json-server';
|
|
232
|
+
import { createServer, generateOpenApi, startServer } from '@kollors/deep-json-server';
|
|
201
233
|
|
|
202
234
|
const server = await createServer({ databasePath: 'mock/database.json', logger: false });
|
|
203
235
|
|
|
@@ -206,6 +238,8 @@ const response = await server.inject({ method: 'GET', url: '/movies' });
|
|
|
206
238
|
await server.close();
|
|
207
239
|
|
|
208
240
|
await startServer({ databasePath: 'mock/database.json', host: '127.0.0.1', port: 4001 });
|
|
241
|
+
|
|
242
|
+
await generateOpenApi({ databasePath: 'mock/database.json', schemaPath: 'mock/database-schema.json', outputPath: 'mock/openapi-schema.yaml' });
|
|
209
243
|
```
|
|
210
244
|
|
|
211
245
|
`createServer()` is useful for tests because it returns a Fastify instance without opening a network port.
|
package/README.ru.md
CHANGED
|
@@ -17,7 +17,8 @@ npm install --save-dev @kollors/deep-json-server
|
|
|
17
17
|
```json
|
|
18
18
|
{
|
|
19
19
|
"scripts": {
|
|
20
|
-
"mock": "deep-json-server mock/database.json --port 4001"
|
|
20
|
+
"mock": "deep-json-server mock/database.json --port 4001",
|
|
21
|
+
"openapi": "deep-json-server mock/database.json --generate mock/database-schema.json mock/openapi-schema.yaml"
|
|
21
22
|
}
|
|
22
23
|
}
|
|
23
24
|
```
|
|
@@ -30,6 +31,37 @@ npm run mock
|
|
|
30
31
|
|
|
31
32
|
По умолчанию сервер доступен по адресу `http://127.0.0.1:4001`. Адрес и порт можно задать через `--host` и `--port` либо переменные окружения `HOST` и `PORT`.
|
|
32
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
|
+
|
|
33
65
|
## Пример базы данных
|
|
34
66
|
|
|
35
67
|
Пример основан на каталоге фильмов. В нём намеренно нет сущности одежды. Используются реальные жанры фильмов, а `Гангстерский фильм` демонстрирует связь с родительским жанром.
|
|
@@ -197,7 +229,7 @@ GET /countries/1?_embed=users
|
|
|
197
229
|
## Программный API
|
|
198
230
|
|
|
199
231
|
```js
|
|
200
|
-
import { createServer, startServer } from '@kollors/deep-json-server';
|
|
232
|
+
import { createServer, generateOpenApi, startServer } from '@kollors/deep-json-server';
|
|
201
233
|
|
|
202
234
|
const server = await createServer({ databasePath: 'mock/database.json', logger: false });
|
|
203
235
|
|
|
@@ -206,6 +238,8 @@ const response = await server.inject({ method: 'GET', url: '/movies' });
|
|
|
206
238
|
await server.close();
|
|
207
239
|
|
|
208
240
|
await startServer({ databasePath: 'mock/database.json', host: '127.0.0.1', port: 4001 });
|
|
241
|
+
|
|
242
|
+
await generateOpenApi({ databasePath: 'mock/database.json', schemaPath: 'mock/database-schema.json', outputPath: 'mock/openapi-schema.yaml' });
|
|
209
243
|
```
|
|
210
244
|
|
|
211
245
|
`createServer()` удобен для тестов: он возвращает экземпляр Fastify, не открывая сетевой порт.
|