@kollors/deep-json-server 0.1.0 → 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 +38 -2
- package/README.ru.md +38 -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
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
[English](README.md) | [Русский](README.ru.md)
|
|
4
4
|
|
|
5
|
+
[GitHub](https://github.com/kollors/deep-json-server) | [npm](https://www.npmjs.com/package/@kollors/deep-json-server)
|
|
6
|
+
|
|
5
7
|
A small JSON REST mock server with CRUD, pagination, deep filters and recursive relationship embedding. It keeps the database in one readable JSON file and infers soft relations from conventional keys such as `countryId`, `genreIds` and `publisherIds`.
|
|
6
8
|
|
|
7
9
|
## Installation
|
|
@@ -15,7 +17,8 @@ Add a script to `package.json`:
|
|
|
15
17
|
```json
|
|
16
18
|
{
|
|
17
19
|
"scripts": {
|
|
18
|
-
"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"
|
|
19
22
|
}
|
|
20
23
|
}
|
|
21
24
|
```
|
|
@@ -28,6 +31,37 @@ npm run mock
|
|
|
28
31
|
|
|
29
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.
|
|
30
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
|
+
|
|
31
65
|
## Example database
|
|
32
66
|
|
|
33
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.
|
|
@@ -195,7 +229,7 @@ They are soft references: the server resolves them when requested but does not e
|
|
|
195
229
|
## Programmatic API
|
|
196
230
|
|
|
197
231
|
```js
|
|
198
|
-
import { createServer, startServer } from '@kollors/deep-json-server';
|
|
232
|
+
import { createServer, generateOpenApi, startServer } from '@kollors/deep-json-server';
|
|
199
233
|
|
|
200
234
|
const server = await createServer({ databasePath: 'mock/database.json', logger: false });
|
|
201
235
|
|
|
@@ -204,6 +238,8 @@ const response = await server.inject({ method: 'GET', url: '/movies' });
|
|
|
204
238
|
await server.close();
|
|
205
239
|
|
|
206
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' });
|
|
207
243
|
```
|
|
208
244
|
|
|
209
245
|
`createServer()` is useful for tests because it returns a Fastify instance without opening a network port.
|
package/README.ru.md
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
[Русский](README.ru.md) | [English](README.md)
|
|
4
4
|
|
|
5
|
+
[GitHub](https://github.com/kollors/deep-json-server) | [npm](https://www.npmjs.com/package/@kollors/deep-json-server)
|
|
6
|
+
|
|
5
7
|
Небольшой JSON REST mock-сервер с CRUD, пагинацией, глубокой фильтрацией и рекурсивной загрузкой связей. База данных хранится в одном читаемом JSON-файле, а мягкие связи определяются по соглашениям о нейминге ключей: `countryId`, `genreIds`, `publisherIds` и так далее.
|
|
6
8
|
|
|
7
9
|
## Установка
|
|
@@ -15,7 +17,8 @@ npm install --save-dev @kollors/deep-json-server
|
|
|
15
17
|
```json
|
|
16
18
|
{
|
|
17
19
|
"scripts": {
|
|
18
|
-
"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"
|
|
19
22
|
}
|
|
20
23
|
}
|
|
21
24
|
```
|
|
@@ -28,6 +31,37 @@ npm run mock
|
|
|
28
31
|
|
|
29
32
|
По умолчанию сервер доступен по адресу `http://127.0.0.1:4001`. Адрес и порт можно задать через `--host` и `--port` либо переменные окружения `HOST` и `PORT`.
|
|
30
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
|
+
|
|
31
65
|
## Пример базы данных
|
|
32
66
|
|
|
33
67
|
Пример основан на каталоге фильмов. В нём намеренно нет сущности одежды. Используются реальные жанры фильмов, а `Гангстерский фильм` демонстрирует связь с родительским жанром.
|
|
@@ -195,7 +229,7 @@ GET /countries/1?_embed=users
|
|
|
195
229
|
## Программный API
|
|
196
230
|
|
|
197
231
|
```js
|
|
198
|
-
import { createServer, startServer } from '@kollors/deep-json-server';
|
|
232
|
+
import { createServer, generateOpenApi, startServer } from '@kollors/deep-json-server';
|
|
199
233
|
|
|
200
234
|
const server = await createServer({ databasePath: 'mock/database.json', logger: false });
|
|
201
235
|
|
|
@@ -204,6 +238,8 @@ const response = await server.inject({ method: 'GET', url: '/movies' });
|
|
|
204
238
|
await server.close();
|
|
205
239
|
|
|
206
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' });
|
|
207
243
|
```
|
|
208
244
|
|
|
209
245
|
`createServer()` удобен для тестов: он возвращает экземпляр Fastify, не открывая сетевой порт.
|