Skip to content

Commit a963efa

Browse files
feat: Add keepRelationFields
* feat: Added forceAnyOf prop * docs: Added docs coverage * feat: Added keepRelationFields option
1 parent 42e6ead commit a963efa

File tree

4 files changed

+440
-11
lines changed

4 files changed

+440
-11
lines changed

README.md

Lines changed: 114 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,10 +60,11 @@ The generator currently supports a few options
6060
| Key | Default Value | Description |
6161
| ------------------------ | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
6262
| keepRelationScalarFields | "false" | By default, the JSON Schema that's generated will output only objects for related model records. If set to "true", this will cause the generator to also output foreign key fields for related records |
63+
| keepRelationFields | "true" | Determines whether to include fields from related models in the generated schema. Setting it to `"false"` allows excluding related model fields from the schema. |
6364
| schemaId | undefined | Add an id to the generated schema. All references will include the schema id |
6465
| includeRequiredFields | "false" | If this flag is `"true"` all required scalar prisma fields that do not have a default value, will be added to the `required` properties field for that schema definition. |
6566
| persistOriginalType | "false" | If this flag is `"true"` the original type will be outputed under the property key "originalType" |
66-
| forceAnyOf | "false" | If this flag is `"true"` the union types will be forced to use `anyOf`. Check [contradictory types](https://ajv.js.org/strict-mode.html#contradictory-types) for details |
67+
| forceAnyOf | "false" | If this flag is `"true"` the union types will be forced to use `anyOf`. Check [contradictory types](https://ajv.js.org/strict-mode.html#contradictory-types) for details |
6768

6869
**3. Run generation**
6970

@@ -308,6 +309,118 @@ Output:
308309
}
309310
```
310311

312+
### No relation fields
313+
314+
For some use cases, it might be useful to not include relation fields in the generated schema. This can be achieved by setting the `keepRelationFields` option to `"false"` and the `keepRelationScalarFields` option to `"true"`. For example if you want to use the generated schema to validate POST request object for instance, you might want to use this option.
315+
316+
```prisma
317+
datasource db {
318+
provider = "postgresql"
319+
url = env("DATABASE_URL")
320+
}
321+
322+
generator jsonSchema {
323+
provider = "prisma-json-schema-generator"
324+
keepRelationScalarFields = "true" // default is "false"
325+
keepRelationFields = "false" // default is "true"
326+
}
327+
328+
model User {
329+
id Int @id @default(autoincrement())
330+
createdAt DateTime @default(now())
331+
email String @unique
332+
weight Float?
333+
is18 Boolean?
334+
name String?
335+
number BigInt @default(34534535435353)
336+
favouriteDecimal Decimal
337+
bytes Bytes
338+
successorId Int? @unique
339+
successor User? @relation("BlogOwnerHistory", fields: [successorId], references: [id])
340+
predecessor User? @relation("BlogOwnerHistory")
341+
role Role @default(USER)
342+
posts Post[]
343+
keywords String[]
344+
biography Json
345+
}
346+
347+
model Post {
348+
id Int @id @default(autoincrement())
349+
user User? @relation(fields: [userId], references: [id])
350+
userId Int?
351+
}
352+
353+
enum Role {
354+
USER
355+
ADMIN
356+
}
357+
```
358+
359+
Output:
360+
361+
```javascript
362+
{
363+
$schema: 'http://json-schema.org/draft-07/schema#',
364+
definitions: {
365+
Post: {
366+
properties: {
367+
id: { type: 'integer' },
368+
userId: { type: ['integer', 'null'] },
369+
},
370+
type: 'object',
371+
},
372+
User: {
373+
properties: {
374+
biography: {
375+
type: [
376+
'number',
377+
'string',
378+
'boolean',
379+
'object',
380+
'array',
381+
'null'
382+
],
383+
},
384+
createdAt: { format: 'date-time', type: 'string' },
385+
email: {
386+
description: 'Triple Slash Comment: Will show up in JSON schema [EMAIL]',
387+
type: 'string'
388+
},
389+
id: { type: 'integer' },
390+
is18: { type: ['boolean', 'null'] },
391+
keywords: { items: { type: 'string' }, type: 'array' },
392+
name: { type: ['string', 'null'] },
393+
number: { type: 'integer', default: '34534535435353' },
394+
posts: {
395+
items: { $ref: '#/definitions/Post' },
396+
type: 'array',
397+
},
398+
bytes: {
399+
description: 'Triple Slash Inline Comment: Will show up in JSON schema [BYTES]',
400+
type: 'string'
401+
},
402+
favouriteDecimal: { type: 'number' },
403+
predecessor: {
404+
anyOf: [
405+
{ $ref: '#/definitions/User' },
406+
{ type: 'null' },
407+
],
408+
},
409+
role: { enum: ['USER', 'ADMIN'], type: 'string', default: 'USER' },
410+
successorId: { type: ['integer', 'null'] },
411+
weight: { type: ['integer', 'null'] },
412+
},
413+
type: 'object',
414+
},
415+
},
416+
properties: {
417+
post: { $ref: '#/definitions/Post' },
418+
user: { $ref: '#/definitions/User' },
419+
},
420+
type: 'object',
421+
}
422+
```
423+
311424
## License: MIT
312425

313426
Copyright (c) 2020 Valentin Palkovič

src/generator/model.ts

Lines changed: 38 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,16 @@ function getRelationScalarFields(model: DMMF.Model): string[] {
77
return model.fields.flatMap((field) => field.relationFromFields || [])
88
}
99

10+
const getRelationFieldNames = (model: DMMF.Model): string[] => {
11+
return model.fields
12+
.filter(
13+
(field) =>
14+
field.relationFromFields?.length ||
15+
field.relationToFields?.length,
16+
)
17+
.map((field) => field.name)
18+
}
19+
1020
export function getJSONSchemaModel(
1121
modelMetaData: ModelMetaData,
1222
transformOptions: TransformOptions,
@@ -20,22 +30,40 @@ export function getJSONSchemaModel(
2030
([name, definition]) => [name, definition] as DefinitionMap,
2131
)
2232
const relationScalarFields = getRelationScalarFields(model)
33+
const relationFieldNames = getRelationFieldNames(model)
2334
const propertiesWithoutRelationScalars = propertiesMap.filter(
24-
(prop) =>
25-
relationScalarFields.findIndex((field) => field === prop[0]) ===
26-
-1,
27-
)
28-
29-
const properties = Object.fromEntries(
30-
transformOptions?.keepRelationScalarFields === 'true'
31-
? propertiesMap
32-
: propertiesWithoutRelationScalars,
35+
(prop) => !relationScalarFields.includes(prop[0]),
3336
)
3437

3538
const definition: JSONSchema7Definition = {
3639
type: 'object',
37-
properties,
40+
properties: {},
41+
}
42+
43+
if (transformOptions.keepRelationScalarFields === 'true') {
44+
if (transformOptions.keepRelationFields === 'false') {
45+
definition.properties = Object.fromEntries(
46+
propertiesMap.filter(
47+
(prop) => !relationFieldNames.includes(prop[0]),
48+
),
49+
)
50+
} else {
51+
definition.properties = Object.fromEntries(propertiesMap)
52+
}
53+
} else {
54+
if (transformOptions.keepRelationFields === 'false') {
55+
definition.properties = Object.fromEntries(
56+
propertiesWithoutRelationScalars.filter(
57+
(prop) => !relationFieldNames.includes(prop[0]),
58+
),
59+
)
60+
} else {
61+
definition.properties = Object.fromEntries(
62+
propertiesWithoutRelationScalars,
63+
)
64+
}
3865
}
66+
3967
if (transformOptions.includeRequiredFields) {
4068
const required = definitionPropsMap.reduce(
4169
(filtered: string[], [name, , fieldMetaData]) => {

src/generator/types.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ export type PropertyMap = [...DefinitionMap, PropertyMetaData]
1616

1717
export interface TransformOptions {
1818
keepRelationScalarFields?: 'true' | 'false'
19+
keepRelationFields?: 'true' | 'false'
1920
schemaId?: string
2021
includeRequiredFields?: 'true' | 'false'
2122
persistOriginalType?: 'true' | 'false'

0 commit comments

Comments
 (0)