UNPKG

single-source-of-truth

Version:
76 lines 2.49 kB
export function parseFieldSchema(name, schema) { const { current, attributes } = flattenSchemaChain(schema); const [kind, type] = resolveKindAndType(current.def); return { name, kind, type, attributes }; } function flattenSchemaChain(schema) { const attributes = {}; let current = schema; let next = schema; while (next) { const payload = extractSchemaAttributes(next); for (const [key, value] of Object.entries(payload.attributes)) Reflect.set(attributes, key, value); current = payload.current; next = payload.next; } return { current, attributes }; } function extractSchemaAttributes(schema) { const attributes = {}; if (schema.def?.[' id']) attributes.id = true; if (schema.def?.[' unique']) attributes.unique = true; if (schema.def?.[' name']) attributes.name = schema.def[' name']; if (schema.def?.[' references']) attributes.references = schema.def[' references']; if (schema.def.type === 'nullable') attributes.nullable = true; if (schema.def.type === 'array') attributes.list = true; return { current: schema, next: unwrapNestedSchema(schema), attributes, }; } function unwrapNestedSchema(schema) { if ('unwrap' in schema && typeof schema.unwrap === 'function') return schema.unwrap(); if ('element' in schema) return schema.element; return null; } function resolveKindAndType(def) { if (def.type === 'enum') { const enumDef = def; if ('name' in enumDef && enumDef.name) return ['enum', enumDef.name]; return ['scalar', 'string']; } if (def.type === 'object') { const objectDef = def; if ('name' in objectDef && objectDef.name) return ['object', objectDef.name]; return ['scalar', 'object']; } if (def.type === 'string') return ['scalar', 'string']; if (def.type === 'number') { const numberDef = def; console.log(numberDef); return numberDef.format === 'safeint' ? ['scalar', 'integer'] : ['scalar', 'float']; } if (def.type === 'boolean') return ['scalar', 'boolean']; if (def.type === 'date') return ['scalar', 'date']; if (def.type === 'bigint') return ['scalar', 'bigint']; throw new Error(`Failed to resolve type for ${def.type}`); } //# sourceMappingURL=field.js.map