forked from keystonejs/keystone
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
310 lines (279 loc) · 10.6 KB
/
Copy pathindex.ts
File metadata and controls
310 lines (279 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
// this file generates the GraphQL filter types for most of our fields.
// generating them from the prisma information isn't really about time or convenience.
// it's about clearly showing what the rules for getting the filters are and what the exceptions are.
import { deepStrictEqual } from 'assert';
import { isDeepStrictEqual } from 'util';
import fs from 'fs-extra';
import { DMMF } from '@prisma/generator-helper';
import { getDMMF } from '@prisma/internals';
import { format, resolveConfig } from 'prettier';
const providers = ['postgresql', 'sqlite', 'mysql'] as const;
type Provider = typeof providers[number];
// https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#model-field-scalar-types
// only the prisma scalars that we currently use are here because adding one requires choosing a graphql scalar
// we can add them when we want field types for those scalars
// the missing ones are:
// - Bytes
// - Json
// - Unsupported (this one can't be interacted with in the prisma client (and therefore cannot be filtered) so it's irrelevant here)
const scalarTypes = ['String', 'Boolean', 'Int', 'Float', 'DateTime', 'Decimal', 'BigInt'] as const;
const getSchemaForProvider = (provider: Provider) => {
return `datasource ${provider} {
url = env("DATABASE_URL")
provider = "${provider}"
}
generator client {
provider = "prisma-client-js"
}
model Optional {
id Int @id @default(autoincrement())
${scalarTypes.map(scalarType => `${scalarType} ${scalarType}?`).join('\n')}
}
model Required {
id Int @id @default(autoincrement())
${scalarTypes.map(scalarType => `${scalarType} ${scalarType}`).join('\n')}
}
${
provider === 'postgresql'
? `model Many {
id Int @id @default(autoincrement())
${scalarTypes.map(scalarType => `${scalarType} ${scalarType}[]`).join('\n')}
}`
: ''
}
`;
};
(async () => {
const prettierConfig = await resolveConfig(`${__dirname}/index.ts`);
assert(prettierConfig !== null);
for (const provider of providers) {
const schema = getSchemaForProvider(provider);
const dmmf = await getDMMF({ datamodel: schema });
await fs.outputFile(
`${__dirname}/generated/${provider}.json`,
JSON.stringify(dmmf.schema.inputObjectTypes, null, 2)
);
const types = getInputTypesByName(dmmf.schema.inputObjectTypes.prisma);
const rootTypes = scalarTypes.flatMap((scalar: string) => {
if (scalar === 'Boolean') {
scalar = 'Bool';
}
if (scalar === 'SomeEnum') {
// the filter types have to be generic over the enum so it's just easier to write it out manually
// but we still want this here to snapshot what the filters look like for a given prisma version & provider combination
return [];
}
let types = [`${scalar}NullableFilter`, `${scalar}Filter`];
if (provider === 'postgresql') {
// i'm not sure this is says nullable when they're not nullable?
// i don't think there is a nullable and non-nullable list?
types.push(`${scalar}NullableListFilter`);
}
return types;
});
for (const typeName of Object.keys(types)) {
replaceNestedNotFilterTypes(types, typeName);
}
const referencedTypes = new Set<string>();
for (const typeName of rootTypes) {
collectReferencedTypes(types, typeName, referencedTypes);
}
if (provider === 'postgresql') {
deepStrictEqual(
dmmf.schema.enumTypes.prisma.find(x => x.name === 'QueryMode'),
{ name: 'QueryMode', values: ['default', 'insensitive'] }
);
}
await fs.outputFile(
`${__dirname}/generated/only-filters/${provider}.json`,
JSON.stringify(
Object.fromEntries([...referencedTypes].map(typeName => [typeName, types[typeName]])),
null,
2
)
);
const filepath = `${__dirname}/../../packages/core/src/types/filters/providers/${provider}.ts`;
const newContent = format(
`// Do not manually modify this file, it is automatically generated by the package at /prisma-utils in this repo.
// Update the script if you need this file to be different
import { graphql } from '../../schema';
${provider === 'postgresql' ? `import { QueryMode } from '../../next-fields'` : ''}
${[...referencedTypes].map(typeName => printInputTypeForGraphQLTS(typeName, types)).join('\n\n')}
${scalarTypes
.map(scalar => {
const scalarInFilterName = scalar === 'Boolean' ? 'Bool' : scalar;
return `export const ${scalar} = {
optional: ${scalarInFilterName}NullableFilter,
required: ${scalarInFilterName}Filter,
${provider === 'postgresql' ? `many: ${scalarInFilterName}NullableListFilter` : ''}
}`;
})
.join('\n\n')}
export {enumFilters as enum } from '../enum-filter'
`,
{ ...prettierConfig, filepath }
);
if (process.env.VERIFY) {
const contents = await fs.readFile(filepath, 'utf8');
if (contents !== newContent) {
throw new Error(
`The file at ${filepath} is inconsistent with the expected generated contents, please run \`yarn generate-filters\` from the root to update it`
);
}
} else {
await fs.outputFile(filepath, newContent);
}
}
})().catch(x => {
console.error(x);
process.exit(1);
});
function getInputTypesByName(types: DMMF.InputType[]) {
return Object.fromEntries(types.map(x => [x.name, x]));
}
function assert(condition: boolean, message?: string): asserts condition {
if (!condition) {
debugger;
throw new Error(`assertion failed${message === undefined ? '' : `: ${message}`}`);
}
}
function replaceNestedNotFilterTypes(
inputTypesByName: Record<string, DMMF.InputType>,
inputTypeName: string
) {
// we want to not replace the nested filter for strings because we don't replace it on postgresql
// and we want the naming to be the same on SQLite
if (inputTypeName.includes('String')) return;
const inputType = inputTypesByName[inputTypeName];
for (const field of inputType.fields) {
if (field.name === 'not') {
const objectInput = field.inputTypes.find(input => input.namespace === 'prisma');
if (
typeof objectInput?.type === 'string' &&
isDeepStrictEqual(inputType.fields, inputTypesByName[objectInput.type].fields)
) {
objectInput.type = inputTypeName;
}
}
}
}
const expectedScalars = new Set(['Null', 'QueryMode', ...scalarTypes]);
function collectReferencedTypes(
inputTypesByName: Record<string, DMMF.InputType>,
inputTypeName: string,
referencedTypes: Set<string>
) {
referencedTypes.add(inputTypeName);
const inputType = inputTypesByName[inputTypeName];
assert(inputType !== undefined, `could not find input type ${inputTypeName}`);
for (const field of inputType.fields) {
assert(!field.isRequired, 'unexpected required field');
for (const inputType of field.inputTypes) {
assert(typeof inputType.type === 'string', 'unexpected non-type name in input types');
if (inputType.location === 'scalar' || inputType.location === 'enumTypes') {
assert(expectedScalars.has(inputType.type), `unexpected scalar ${inputType.type}`);
continue;
}
assert(inputType.location === 'inputObjectTypes', `unexpected ${inputType.location} type`);
if (!referencedTypes.has(inputType.type)) {
collectReferencedTypes(inputTypesByName, inputType.type, referencedTypes);
}
}
}
}
/**
* Note a field can be both nullable and a list.
*
* Translated into typescript, that means `Array<T> | null`,
* not `Array<T | null>` or `Array<T | null> | null`
*/
type TransformedInputTypeField = {
type: string;
isNullable: boolean;
isList: boolean;
};
function pickInputTypeForField(field: DMMF.SchemaArg): TransformedInputTypeField {
assert(!field.isRequired, 'unexpected required field');
// null is already represented with field.isNullable
const inputTypesWithoutNull = field.inputTypes.filter(type => {
if (type.type === 'Null') {
assert(!type.isList, 'unexpected null list');
assert(field.isNullable, 'unexpected isNullable false when null type in input types');
return false;
}
return true;
});
assert(
inputTypesWithoutNull.length + Number(field.isNullable) === field.inputTypes.length,
'unexpected isNullable false when null type in input types'
);
const inputType = (() => {
if (inputTypesWithoutNull.length === 1) {
return inputTypesWithoutNull[0];
}
assert(
inputTypesWithoutNull.length === 2,
'unexpected more than two input types excluding null'
);
const inputType = inputTypesWithoutNull.find(x => x.location == 'inputObjectTypes');
assert(
!!inputType,
'could not find input object type when more than one input type excluding null'
);
return inputType;
})();
assert(typeof inputType.type === 'string');
return {
isList: inputType.isList,
isNullable: field.isNullable,
type: scalarsToGqlScalars[inputType.type] ?? inputType.type,
};
}
function printInputTypeForGraphQLTS(
inputTypeName: string,
inputTypesByName: Record<string, DMMF.InputType>
) {
const inputType = inputTypesByName[inputTypeName];
assert(inputType !== undefined, `could not find input type ${inputTypeName}`);
const expectedMaxMinNumFields = inputTypeName.endsWith('NullableListFilter') ? 1 : null;
assert(inputType.constraints.maxNumFields === expectedMaxMinNumFields);
assert(inputType.constraints.minNumFields === expectedMaxMinNumFields);
const nameOfInputObjectTypeType = `${inputTypeName}Type`;
const fields = inputType.fields.map(x => [x.name, pickInputTypeForField(x)] as const);
return `type ${nameOfInputObjectTypeType} = graphql.InputObjectType<{
${fields
.map(([name, field]) => {
return `${field.isNullable ? '// can be null\n' : ''}${name}: graphql.Arg<${
field.isList
? `graphql.ListType<graphql.NonNullType<typeof ${field.type}>>`
: `typeof ${field.type}`
}>`;
})
.join(',\n')}
}>
const ${inputTypeName}: ${nameOfInputObjectTypeType} = graphql.inputObject({
name: '${
// we want to use Boolean instead of Bool because GraphQL calls it Boolean
inputTypeName.replace('Bool', 'Boolean')
}',
fields: () => ({
${fields
.map(([name, field]) => {
return `${field.isNullable ? '// can be null\n' : ''}${name}: graphql.arg({ type: ${
field.isList ? `graphql.list(graphql.nonNull(${field.type}))` : field.type
} })`;
})
.join(',\n')}
})
})`;
}
const scalarsToGqlScalars: Record<string, string> = {
String: 'graphql.String',
Boolean: 'graphql.Boolean',
Int: 'graphql.Int',
Float: 'graphql.Float',
Json: 'graphql.JSON',
DateTime: 'graphql.DateTime',
Decimal: 'graphql.Decimal',
BigInt: 'graphql.BigInt',
};