Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Correctly validate optional enums #1454

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ model User {
successor User? @relation("BlogOwnerHistory", fields: [successorId], references: [id])
predecessor User? @relation("BlogOwnerHistory")
role Role @default(USER)
secondRole Role?
posts Post[]
keywords String[]
biography Json
Expand Down
8 changes: 6 additions & 2 deletions src/generator/properties.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,13 +145,17 @@ function isSingleReference(field: DMMF.Field) {
}

function getEnumListByDMMFType(modelMetaData: ModelMetaData) {
return (field: DMMF.Field): string[] | undefined => {
return (field: DMMF.Field): (string | null)[] | undefined => {
const enumItem = modelMetaData.enums.find(
({ name }) => name === field.type,
)

if (!enumItem) return undefined
return enumItem.values.map((item) => item.name)
const items: (string | null)[] = enumItem.values.map((item) => item.name)
if (!field.isRequired) {
items.push(null)
}
return items
}
}

Expand Down
158 changes: 157 additions & 1 deletion src/tests/generator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const datamodelPostGresQL = /* Prisma */ `
successor User? @relation("BlogOwnerHistory", fields: [successorId], references: [id])
predecessor User? @relation("BlogOwnerHistory")
role Role @default(USER)
secondRole Role?
posts Post[]
keywords String[]
biography Json
Expand Down Expand Up @@ -147,6 +148,10 @@ describe('JSON Schema Generator', () => {
enum: ['USER', 'ADMIN'],
type: 'string',
},
secondRole: {
type: ['string', 'null'],
enum: ['USER', 'ADMIN', null],
},
successor: {
anyOf: [
{ $ref: '#/definitions/User' },
Expand Down Expand Up @@ -247,6 +252,10 @@ describe('JSON Schema Generator', () => {
enum: ['USER', 'ADMIN'],
type: 'string',
},
secondRole: {
type: ['string', 'null'],
enum: ['USER', 'ADMIN', null],
},
successor: {
anyOf: [
{ $ref: '#/definitions/User' },
Expand Down Expand Up @@ -346,6 +355,10 @@ describe('JSON Schema Generator', () => {
enum: ['USER', 'ADMIN'],
type: 'string',
},
secondRole: {
type: ['string', 'null'],
enum: ['USER', 'ADMIN', null],
},
successor: {
anyOf: [
{ $ref: '#/definitions/User' },
Expand Down Expand Up @@ -427,6 +440,10 @@ describe('JSON Schema Generator', () => {
enum: ['USER', 'ADMIN'],
type: 'string',
},
secondRole: {
type: ['string', 'null'],
enum: ['USER', 'ADMIN', null],
},
weight: {
default: 333.33,
type: ['number', 'null'],
Expand Down Expand Up @@ -508,6 +525,10 @@ describe('JSON Schema Generator', () => {
enum: ['USER', 'ADMIN'],
type: 'string',
},
secondRole: {
type: ['string', 'null'],
enum: ['USER', 'ADMIN', null],
},
successorId: {
default: 123,
type: ['integer', 'null'],
Expand Down Expand Up @@ -604,6 +625,10 @@ describe('JSON Schema Generator', () => {
enum: ['USER', 'ADMIN'],
type: 'string',
},
secondRole: {
type: ['string', 'null'],
enum: ['USER', 'ADMIN', null],
},
successor: {
anyOf: [
{ $ref: '#/definitions/User' },
Expand Down Expand Up @@ -721,6 +746,11 @@ describe('JSON Schema Generator', () => {
enum: ['USER', 'ADMIN'],
type: 'string',
},
secondRole: {
type: ['string', 'null'],
enum: ['USER', 'ADMIN', null],
originalType: 'Role',
},
successor: {
anyOf: [
{ $ref: '#/definitions/User' },
Expand Down Expand Up @@ -824,6 +854,10 @@ describe('JSON Schema Generator', () => {
enum: ['USER', 'ADMIN'],
type: 'string',
},
secondRole: {
anyOf: [{ type: 'string' }, { type: 'null' }],
enum: ['USER', 'ADMIN', null],
},
successor: {
anyOf: [
{ $ref: '#/definitions/User' },
Expand Down Expand Up @@ -919,6 +953,10 @@ describe('JSON Schema Generator', () => {
enum: ['USER', 'ADMIN'],
type: 'string',
},
secondRole: {
type: ['string', 'null'],
enum: ['USER', 'ADMIN', null],
},
successor: {
anyOf: [
{ $ref: '#/definitions/User' },
Expand Down Expand Up @@ -1023,6 +1061,10 @@ describe('JSON Schema Generator', () => {
enum: ['USER', 'ADMIN'],
type: 'string',
},
secondRole: {
type: ['string', 'null'],
enum: ['USER', 'ADMIN', null],
},
successor: {
anyOf: [
{ $ref: 'schemaId#/definitions/User' },
Expand Down Expand Up @@ -1050,7 +1092,63 @@ describe('JSON Schema Generator', () => {
})

// eslint-disable-next-line jest/expect-expect
it('generated schema validates against input', async () => {
it('generated schema validates against input 1', async () => {
const dmmf = await getDMMF({ datamodel: datamodelPostGresQL })
const jsonSchema = transformDMMF(dmmf, {
persistOriginalType: 'true',
})
const ajv = new Ajv({
allowUnionTypes: true,
}).addKeyword('originalType')

addFormats(ajv)

const validate = ajv.compile(jsonSchema)
const valid = validate({
post: {
id: 0,
user: {
id: 100,
},
},
user: {
id: 10,
createdAt: '1997-07-16T19:20:30.45+01:00',
email: 'jan@scharnow.city',
biography: {
bornIn: 'Scharnow',
},
number: 34534535435353,
bytes: 'SGVsbG8gd29ybGQ=',
favouriteDecimal: 22.32,
is18: true,
keywords: ['prisma2', 'json-schema', 'generator'],
name: null,
posts: [
{
id: 4,
},
{
id: 20,
},
],
predecessor: {
id: 10,
email: 'horst@wassermann.de',
},
successor: null,
role: 'USER',
weight: 10.12,
},
})

if (!valid) {
throw new Error(ajv.errorsText(validate.errors))
}
})

// eslint-disable-next-line jest/expect-expect
it('generated schema validates against input 2', async () => {
const dmmf = await getDMMF({ datamodel: datamodelPostGresQL })
const jsonSchema = transformDMMF(dmmf, {
persistOriginalType: 'true',
Expand Down Expand Up @@ -1096,6 +1194,7 @@ describe('JSON Schema Generator', () => {
},
successor: null,
role: 'USER',
secondRole: null,
weight: 10.12,
},
})
Expand All @@ -1105,6 +1204,63 @@ describe('JSON Schema Generator', () => {
}
})

// eslint-disable-next-line jest/expect-expect
it('generated schema validates against input 3', async () => {
const dmmf = await getDMMF({ datamodel: datamodelPostGresQL })
const jsonSchema = transformDMMF(dmmf, {
persistOriginalType: 'true',
})
const ajv = new Ajv({
allowUnionTypes: true,
}).addKeyword('originalType')

addFormats(ajv)

const validate = ajv.compile(jsonSchema)
const valid = validate({
post: {
id: 0,
user: {
id: 100,
},
},
user: {
id: 10,
createdAt: '1997-07-16T19:20:30.45+01:00',
email: 'jan@scharnow.city',
biography: {
bornIn: 'Scharnow',
},
number: 34534535435353,
bytes: 'SGVsbG8gd29ybGQ=',
favouriteDecimal: 22.32,
is18: true,
keywords: ['prisma2', 'json-schema', 'generator'],
name: null,
posts: [
{
id: 4,
},
{
id: 20,
},
],
predecessor: {
id: 10,
email: 'horst@wassermann.de',
},
successor: null,
role: 'USER',
secondRole: 'ADMIN',
weight: 10.12,
},
})

if (!valid) {
throw new Error(ajv.errorsText(validate.errors))
}
});

it('nullable anyOf field', async () => {
const dmmf = await getDMMF({
datamodel: datamodelPostGresQL_anyOfCheck,
Expand Down