Skip to content

Commit a779835

Browse files
committed
import types
1 parent a2a5c47 commit a779835

File tree

4 files changed

+99
-75
lines changed

4 files changed

+99
-75
lines changed

src/collections/Generator.ts

+64-52
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ const Generator: CollectionConfig = {
8989
if (!context.internal) context.internal = []
9090
;(context.internal as string[])?.push('schemas.afterHook')
9191
// #region Retrieve data
92-
const schemas: any = {}
92+
const schemas: Record<string, Schema> = {}
9393

9494
const [graphSchemas, nouns, constraintSpans, examples, jsons] = (await Promise.all([
9595
payload
@@ -198,22 +198,21 @@ const Generator: CollectionConfig = {
198198
processUnarySchemas(graphSchemas, nouns, nounRegex, schemas, jsonExamples, examples)
199199
// #region Schema processor
200200
// Flatten allOf chains in order to help parsing engines that don't support them
201-
const componentSchemas: [string, JSONSchema][] = Object.entries(schemas)
201+
const componentSchemas: [string, Schema][] = Object.entries(schemas)
202202
for (const [key, schema] of componentSchemas) {
203203
while (schema.allOf) {
204204
const mergedRequired: string[] = [...(schema.required || [])]
205205
let mergedProperties = schema.properties || {}
206-
const mergedAllOf: JSONSchema[] = []
207-
schema.allOf.forEach((s: any) => {
208-
const dependency = schemas[s.$ref?.split('/').pop()]
206+
const mergedAllOf: JSONSchemaDefinition[] = []
207+
schema.allOf.forEach((s) => {
208+
const dependency = schemas[(s as JSONSchema).$ref?.split('/').pop() || '']
209209
if (dependency.required?.length)
210210
mergedRequired.push(
211211
...dependency.required.filter((f: string) => !mergedRequired.includes(f)),
212212
)
213213
if (Object.keys(dependency.properties || {}).length)
214214
mergedProperties = { ...dependency.properties, ...mergedProperties }
215-
if (dependency.allOf?.length)
216-
mergedAllOf.push(...dependency.allOf.map((a: JSONSchema) => a))
215+
if (dependency.allOf?.length) mergedAllOf.push(...dependency.allOf.map((a) => a))
217216
if (!schema.title && dependency.title) schema.title = dependency.title
218217
if (!schema.description && dependency.description)
219218
schema.description = dependency.description
@@ -318,9 +317,12 @@ const Generator: CollectionConfig = {
318317
paths: Object.fromEntries(
319318
Object.entries(schemas)
320319
.filter(([key, _schema]) => schemas['Update' + key] || schemas['New' + key])
321-
.flatMap(([key, schema]: [string, any]) => {
320+
.flatMap(([key, schema]: [string, Schema]) => {
322321
const baseSchema = schemas['Update' + key] || schemas['New' + key] || schema
323-
const idScheme: [PropertyKey, any][] | undefined = getIdScheme(baseSchema, schemas)
322+
const idScheme: [PropertyKey, JSONSchemaDefinition][] | undefined = getIdScheme(
323+
baseSchema,
324+
schemas,
325+
)
324326
const subject = nouns.find((n) => nameToKey(n.name || '') === key)
325327
const permissions = (
326328
subject?.permissions || ['create', 'read', 'update', 'list', 'login', 'rateLimit']
@@ -352,9 +354,10 @@ const Generator: CollectionConfig = {
352354
// #region Add paths for CRUD operations based on permissions
353355
const basePath = `/${nameToKey(plural).toLowerCase()}`
354356
if (permissions.includes('list')) {
355-
const wrapperTemplate = _.cloneDeep(globalWrapperTemplate) as {
356-
[key: string]: any
357-
}
357+
const wrapperTemplate = _.cloneDeep(globalWrapperTemplate) as Record<
358+
string,
359+
Schema
360+
>
358361
const pathParameters = []
359362
const operationParameters = []
360363
if (databaseEngine === 'Payload') {
@@ -559,7 +562,7 @@ const Generator: CollectionConfig = {
559562
if (permissions.includes('create')) {
560563
const createSchema: JSONSchema | undefined = fillSchemaTemplate({
561564
schema: { $ref: `#/components/schemas/${schema.$id}` },
562-
wrapperTemplate: globalWrapperTemplate,
565+
wrapperTemplate: globalWrapperTemplate as Record<string, Schema>,
563566
replacementFieldPath,
564567
})
565568
postUsed = true
@@ -574,7 +577,7 @@ const Generator: CollectionConfig = {
574577
_.set(createError, errorCodePath || 'error.code', 400)
575578
}
576579

577-
const create: any = {
580+
const create = {
578581
summary: `${isId ? 'Create' : 'Add'} ${nounIsPlural ? '' : 'a '}new ${title}`,
579582
operationId: `post-${key.toLowerCase()}`,
580583
responses: {
@@ -667,11 +670,11 @@ const Generator: CollectionConfig = {
667670
const parameters =
668671
(idScheme?.length &&
669672
idScheme.map((id) => ({
670-
schema: { type: id[1].type },
673+
schema: { type: (id[1] as JSONSchema).type },
671674
name: id[0],
672675
in: 'path',
673676
required: true,
674-
description: id[1].description,
677+
description: (id[1] as JSONSchema).description,
675678
}))) ||
676679
[]
677680
if (databaseEngine === 'Payload') {
@@ -693,7 +696,7 @@ const Generator: CollectionConfig = {
693696
if (permissions.includes('read')) {
694697
const readSchema: JSONSchema | undefined = fillSchemaTemplate({
695698
schema: { $ref: `#/components/schemas/${schema.$id}` },
696-
wrapperTemplate: globalWrapperTemplate,
699+
wrapperTemplate: globalWrapperTemplate as Record<string, Schema>,
697700
replacementFieldPath,
698701
})
699702
retval[retval.length - 1][1].get = {
@@ -755,7 +758,7 @@ const Generator: CollectionConfig = {
755758
if (permissions.includes('update')) {
756759
const updateSchema: JSONSchema | undefined = fillSchemaTemplate({
757760
schema: { $ref: `#/components/schemas/${schema.$id}` },
758-
wrapperTemplate: globalWrapperTemplate,
761+
wrapperTemplate: globalWrapperTemplate as Record<string, Schema>,
759762
replacementFieldPath,
760763
})
761764
patchUsed = true
@@ -826,7 +829,7 @@ const Generator: CollectionConfig = {
826829
}
827830
if (permissions.includes('delete')) {
828831
const deleteSchema: JSONSchema | undefined = fillSchemaTemplate({
829-
wrapperTemplate: globalWrapperTemplate,
832+
wrapperTemplate: globalWrapperTemplate as Record<string, Schema>,
830833
})
831834
retval[retval.length - 1][1].delete = {
832835
responses: {
@@ -921,7 +924,7 @@ function processArraySchemas(
921924
arrayTypes: { gs: gdl.GraphSchema; cs: Omit<gdl.ConstraintSpan, 'updatedAt'> }[],
922925
nouns: Omit<gdl.GraphSchema | gdl.Noun, 'updatedAt'>[],
923926
nounRegex: RegExp,
924-
schemas: any,
927+
schemas: Record<string, Schema>,
925928
jsonExamples: { [k: string]: JSONSchemaType },
926929
) {
927930
for (const { gs: schema } of arrayTypes) {
@@ -955,7 +958,7 @@ function processArraySchemas(
955958

956959
function processBinarySchemas(
957960
constraintSpans: Omit<gdl.ConstraintSpan, 'updatedAt'>[],
958-
schemas: any,
961+
schemas: Record<string, Schema>,
959962
nouns: Omit<gdl.GraphSchema | gdl.Noun, 'updatedAt'>[],
960963
jsonExamples: { [k: string]: JSONSchemaType },
961964
nounRegex: RegExp,
@@ -991,7 +994,7 @@ function processBinarySchemas(
991994
.map(
992995
(c) =>
993996
propertySchema.roles?.find(
994-
(r: any) => r.id !== ((c.value as gdl.ConstraintSpan).roles[0] as gdl.Role).id,
997+
(r) => (r as gdl.Role).id !== ((c.value as gdl.ConstraintSpan).roles[0] as gdl.Role).id,
995998
) as gdl.Role,
996999
)
9971000

@@ -1030,11 +1033,11 @@ function processUnarySchemas(
10301033
graphSchemas: Omit<gdl.GraphSchema, 'updatedAt'>[],
10311034
nouns: Omit<gdl.Noun | gdl.GraphSchema, 'updatedAt'>[],
10321035
nounRegex: RegExp,
1033-
schemas: any,
1036+
schemas: Record<string, Schema>,
10341037
jsonExamples: { [k: string]: JSONSchemaType },
10351038
examples: Omit<gdl.Graph, 'updatedAt'>[],
10361039
) {
1037-
for (const unarySchema of graphSchemas.filter((s: any) => s.roles?.length === 1)) {
1040+
for (const unarySchema of graphSchemas.filter((s) => s.roles?.length === 1)) {
10381041
const unaryRole = unarySchema.roles?.[0] as gdl.Role
10391042
const subject = unaryRole?.noun?.value as gdl.Noun | gdl.GraphSchema
10401043
const reading = (unarySchema.readings as gdl.Reading[])?.[0]
@@ -1060,7 +1063,7 @@ function processUnarySchemas(
10601063
.map(
10611064
(c) =>
10621065
unarySchema.roles?.find(
1063-
(r: any) => r.id !== ((c.value as gdl.ConstraintSpan).roles[0] as gdl.Role).id,
1066+
(r) => (r as gdl.Role).id !== ((c.value as gdl.ConstraintSpan).roles[0] as gdl.Role).id,
10641067
) as gdl.Role,
10651068
)
10661069

@@ -1082,7 +1085,7 @@ function processUnarySchemas(
10821085
// #region Helper functions
10831086
function removeDuplicateSchemas(
10841087
patchUsed: boolean,
1085-
schemas: any,
1088+
schemas: Record<string, Schema>,
10861089
key: string,
10871090
replacements: string[][],
10881091
postUsed: boolean,
@@ -1115,15 +1118,15 @@ function removeDuplicateSchemas(
11151118
Object.keys(schemas[key].properties || {}).length))
11161119
) {
11171120
postUsed = false
1118-
const allOf: any = schemas[key].allOf
1121+
const allOf = schemas[key].allOf
11191122
if (!schemas['New' + key]?.allOf) delete schemas[key].allOf
11201123
else if (
1121-
allOf[1] &&
1124+
allOf?.[1] &&
11221125
(schemas['New' + key].allOf?.[0] as JSONSchema).$ref?.replace(/Update|New/, '') ===
1123-
allOf[1].$ref
1126+
(allOf[1] as Schema).$ref
11241127
)
11251128
allOf.splice(0, 1)
1126-
else allOf[0] = schemas['New' + key].allOf?.[0]
1129+
else if (allOf) allOf[0] = schemas['New' + key].allOf?.[0] as Schema
11271130

11281131
const required = schemas[key].required
11291132
schemas[key] = {
@@ -1157,7 +1160,7 @@ function createErrorTemplates(
11571160
)[],
11581161
errorMessagePath: string | null | undefined,
11591162
errorCodePath: string | null | undefined,
1160-
title: any,
1163+
title: string,
11611164
) {
11621165
let unauthorizedError: object | undefined = undefined,
11631166
rateError: object | undefined = undefined,
@@ -1181,40 +1184,40 @@ function createErrorTemplates(
11811184
return { unauthorizedError, rateError, notFoundError }
11821185
}
11831186

1184-
function getIdScheme(baseSchema: any, schemas: any) {
1187+
function getIdScheme(baseSchema: Schema, schemas: Record<string, Schema>) {
11851188
let idSchema = baseSchema
1186-
let idScheme: [PropertyKey, any][] | undefined =
1187-
idSchema?.properties &&
1188-
Object.entries(idSchema.properties)?.filter((p: any) =>
1189-
p[1]?.description?.includes('is uniquely identified by'),
1190-
)
1189+
let idScheme: [PropertyKey, JSONSchemaDefinition][] | undefined = idSchema?.properties
1190+
? Object.entries(idSchema.properties)?.filter((p) =>
1191+
(p[1] as JSONSchema)?.description?.includes('is uniquely identified by'),
1192+
)
1193+
: undefined
11911194
while (!idScheme?.length && idSchema?.allOf) {
11921195
const key = (idSchema.allOf[0] as JSONSchema)?.$ref?.split('/')?.pop() as string
11931196
const bareKey = key.replace(/^New|^Update/, '')
11941197
idSchema = schemas['Update' + bareKey] || schemas['New' + bareKey] || schemas[bareKey]
11951198
idScheme =
11961199
idSchema?.properties &&
1197-
Object.entries(idSchema.properties)?.filter((p: any) =>
1198-
p[1]?.description?.includes('is uniquely identified by'),
1200+
Object.entries(idSchema.properties)?.filter((p) =>
1201+
(p[1] as JSONSchema)?.description?.includes('is uniquely identified by'),
11991202
)
12001203
}
12011204

12021205
if (idScheme?.length)
12031206
for (let i = 0; i < idScheme.length; i++) {
1204-
let value = idScheme[i][1]
1207+
let value = idScheme[i][1] as Schema
12051208
while (value.oneOf) {
12061209
const description = value.description
1207-
value = value.oneOf[0]
1210+
value = value.oneOf[0] as Schema
12081211
if (value.properties) {
12091212
idScheme.splice(
12101213
i,
12111214
1,
1212-
...(Object.entries(value.properties).map((p: [PropertyKey, any]) => [
1215+
...(Object.entries(value.properties).map((p: [PropertyKey, JSONSchemaDefinition]) => [
12131216
p[0],
1214-
{ description, ...p[1] },
1215-
]) as [PropertyKey, any][]),
1217+
{ description, ...(p[1] as JSONSchema) },
1218+
]) as [PropertyKey, JSONSchemaDefinition][]),
12161219
)
1217-
value = idScheme[i][1]
1220+
value = idScheme[i][1] as Schema
12181221
} else idScheme[i][1] = { description, ...value }
12191222
}
12201223
}
@@ -1228,18 +1231,18 @@ function fillSchemaTemplate({
12281231
replacementFieldPath,
12291232
}: {
12301233
schema?: JSONSchema
1231-
example?: any
1232-
wrapperTemplate: any
1233-
replacementFieldPath?: any
1234+
example?: unknown
1235+
wrapperTemplate?: Record<string, Schema>
1236+
replacementFieldPath?: string | null
12341237
}) {
12351238
const jsonSchema = new Draft06()
1236-
if (Object.keys(wrapperTemplate).length) {
1239+
if (wrapperTemplate && Object.keys(wrapperTemplate).length) {
12371240
const wrapperSchema = jsonSchema.createSchemaOf(wrapperTemplate)
12381241
if (replacementFieldPath && _.get(wrapperSchema.properties, replacementFieldPath))
12391242
if (schema) _.set(wrapperSchema.properties, replacementFieldPath, schema)
12401243
else _.unset(wrapperSchema.properties, replacementFieldPath)
12411244
if (example) {
1242-
wrapperTemplate[replacementFieldPath] = example
1245+
wrapperTemplate[replacementFieldPath || ''] = example
12431246
wrapperSchema.examples = [wrapperTemplate]
12441247
}
12451248
schema = wrapperSchema
@@ -1263,7 +1266,7 @@ function createProperty({
12631266
}
12641267
}) {
12651268
object = nouns.find((n) => n.id === object.id) || object
1266-
const property: JSONSchemaDefinition = {}
1269+
const property: Schema = {}
12671270
let { referenceScheme, superType, valueType } = object as gdl.Noun
12681271
if (!referenceScheme) {
12691272
referenceScheme =
@@ -1286,7 +1289,7 @@ function createProperty({
12861289
property.enum = noun.enum.split(',').map((e) => {
12871290
const val = e.trim()
12881291
if (val === 'null') {
1289-
;(property as any).nullable = true
1292+
property.nullable = true
12901293
return null
12911294
}
12921295
return val
@@ -1586,3 +1589,12 @@ export function extractPropertyName(objectReading: string[]) {
15861589
return propertyName
15871590
}
15881591
// #endregion
1592+
1593+
type Schema = JSONSchema & {
1594+
nullable?: true | false
1595+
properties?:
1596+
| {
1597+
[k: string]: Schema
1598+
}
1599+
| undefined
1600+
}

src/collections/GraphSchemas.ts

+5-5
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ const GraphSchemas: CollectionConfig = {
8888
const nounEntities: (gdl.Noun | gdl.GraphSchema)[] = []
8989

9090
// tokenize by noun names
91-
;(readings[0].text as string).split(nounRegex).forEach((token: any) => {
91+
;(readings[0].text as string).split(nounRegex).forEach((token) => {
9292
const noun = entities.find((noun) => noun.name === token)
9393
if (noun) nounEntities.push(noun)
9494
})
@@ -204,7 +204,7 @@ const GraphSchemas: CollectionConfig = {
204204
},
205205
})
206206
if (value === 'many-to-one') {
207-
const constraintSpan = await payload.create({
207+
const _constraintSpan = await payload.create({
208208
collection: 'constraint-spans',
209209
data: {
210210
roles: data?.roles[0] || originalDoc.roles[0],
@@ -220,7 +220,7 @@ const GraphSchemas: CollectionConfig = {
220220
// })
221221
// console.log('roles', roles)
222222
} else if (value === 'one-to-many') {
223-
const constraintSpan = await payload.create({
223+
const _constraintSpan = await payload.create({
224224
collection: 'constraint-spans',
225225
data: {
226226
roles: data?.roles[1] || originalDoc.roles[1],
@@ -236,7 +236,7 @@ const GraphSchemas: CollectionConfig = {
236236
// })
237237
// console.log('roles', roles)
238238
} else if (value === 'many-to-many') {
239-
const constraintSpan = await payload.create({
239+
const _constraintSpan = await payload.create({
240240
collection: 'constraint-spans',
241241
data: {
242242
roles: data?.roles || originalDoc.roles,
@@ -259,7 +259,7 @@ const GraphSchemas: CollectionConfig = {
259259
modality: 'Alethic',
260260
},
261261
})
262-
const constraintSpans = await Promise.all([
262+
const _constraintSpans = await Promise.all([
263263
payload.create({
264264
collection: 'constraint-spans',
265265
data: {

0 commit comments

Comments
 (0)