techtools

models.ts

TypeScript · 55 рядків

1export const primitiveTypes = new Set(['string','number','integer','boolean','object','any','null'])
2const identifier = /^[A-Za-z_][A-Za-z0-9_]*$/
3
4export function referencedModels(schema, refs = new Set()) {
5  for (const value of Object.values(schema || {})) {
6    if (typeof value === 'string') {
7      const type = value.endsWith('[]') ? value.slice(0,-2) : value
8      if (!primitiveTypes.has(type)) refs.add(type)
9    } else if (value && typeof value === 'object' && !Array.isArray(value)) referencedModels(value, refs)
10  }
11  return [...refs]
12}
13
14export function validateModel(input, models, currentId = null) {
15  const errors = []
16  const name = String(input.name || '').trim()
17  if (!identifier.test(name)) errors.push('Name must be a valid identifier')
18  if (models.some(model => model.id !== currentId && model.name === name)) errors.push(`Model "${name}" already exists`)
19  const schema = input.schema
20  if (!schema || typeof schema !== 'object' || Array.isArray(schema)) errors.push('Schema must be a JSON object')
21  const available = new Set(models.filter(model => model.id !== currentId).map(model => model.name)); if (name) available.add(name)
22  function check(value, path) {
23    if (!value || typeof value !== 'object' || Array.isArray(value)) { errors.push(`${path} must be an object`); return }
24    for (const [field,typeValue] of Object.entries(value)) {
25      if (!identifier.test(field)) errors.push(`${path}.${field}: field name must be a valid identifier`)
26      if (typeof typeValue === 'string') {
27        const type = typeValue.endsWith('[]') ? typeValue.slice(0,-2) : typeValue
28        if (!type || (!primitiveTypes.has(type) && !available.has(type))) errors.push(`${path}.${field}: unknown type "${typeValue}"`)
29      } else if (typeValue && typeof typeValue === 'object' && !Array.isArray(typeValue)) check(typeValue,`${path}.${field}`)
30      else errors.push(`${path}.${field}: type must be a string or inline object`)
31    }
32  }
33  if (schema && typeof schema === 'object' && !Array.isArray(schema)) check(schema,'schema')
34  // значення за замовчуванням (P4, R-23 §11): лише поля схеми, типи — як у схемі
35  const defaults = input.defaults
36  if (defaults !== undefined && defaults !== null) {
37    if (typeof defaults !== 'object' || Array.isArray(defaults)) errors.push('Defaults must be a JSON object')
38    else if (schema && typeof schema === 'object' && !Array.isArray(schema)) {
39      const self = { name, schema }
40      for (const [field, value] of Object.entries(defaults)) {
41        if (!(field in schema)) { errors.push(`defaults.${field}: no such field in the schema`); continue }
42        const result = validateData({ [field]: value }, { schema: { [field]: schema[field] } }, [...models.filter(model => model.id !== currentId), self], 'defaults')
43        errors.push(...result.errors)
44      }
45    }
46  }
47  return { valid:errors.length===0, errors, name, schema, defaults: defaults ?? undefined }
48}
49
50export function validateData(data, model, models, path='payload') {
51  const errors=[]
52  function check(value,schema,currentPath){if(!value||typeof value!=='object'||Array.isArray(value)){errors.push(`${currentPath} must be an object`);return}for(const [field,typeSpec] of Object.entries(schema||{}) as [string,any][]){const fieldValue=value[field],fieldPath=`${currentPath}.${field}`;if(fieldValue===undefined){errors.push(`${fieldPath} is required`);continue}if(typeof typeSpec==='object'){check(fieldValue,typeSpec,fieldPath);continue}const array=typeSpec.endsWith('[]'),type=array?typeSpec.slice(0,-2):typeSpec,values=array?(Array.isArray(fieldValue)?fieldValue:(errors.push(`${fieldPath} must be an array`),[])):[fieldValue],reference=models.find(item=>item.name===type);for(const item of values){if(reference)check(item,reference.schema,fieldPath);else if(type==='integer'&&!Number.isInteger(item))errors.push(`${fieldPath} must be an integer`);else if(type==='number'&&typeof item!=='number')errors.push(`${fieldPath} must be a number`);else if(type==='string'&&typeof item!=='string')errors.push(`${fieldPath} must be a string`);else if(type==='boolean'&&typeof item!=='boolean')errors.push(`${fieldPath} must be a boolean`);else if(type==='object'&&(!item||typeof item!=='object'||Array.isArray(item)))errors.push(`${fieldPath} must be an object`);else if(type==='null'&&item!==null)errors.push(`${fieldPath} must be null`)}}}
53  check(data,model?.schema,path);return{valid:errors.length===0,errors}
54}
55