UNPKG

snake-query

Version:
159 lines (130 loc) 3.05 kB
class SchemaBuilder { constructor() { this.schema = {}; } object(properties = {}) { this.schema = { type: 'object', properties: {} }; if (Object.keys(properties).length > 0) { this.schema.properties = properties; } return this; } array(itemSchema) { this.schema = { type: 'array', items: itemSchema || { type: 'object' } }; return this; } string(constraints = {}) { this.schema = { type: 'string', ...constraints }; return this; } number(constraints = {}) { this.schema = { type: 'number', ...constraints }; return this; } integer(constraints = {}) { this.schema = { type: 'number', ...constraints }; return this; } boolean() { this.schema = { type: 'boolean' }; return this; } addProperty(name, schema) { if (!this.schema.properties) { this.schema.properties = {}; } this.schema.properties[name] = schema; return this; } addStringProperty(name, constraints = {}) { return this.addProperty(name, { type: 'string', ...constraints }); } addNumberProperty(name, constraints = {}) { return this.addProperty(name, { type: 'number', ...constraints }); } addIntegerProperty(name, constraints = {}) { return this.addProperty(name, { type: 'number', ...constraints }); } addBooleanProperty(name) { return this.addProperty(name, { type: 'boolean' }); } addArrayProperty(name, itemSchema) { return this.addProperty(name, { type: 'array', items: itemSchema || { type: 'string' } }); } addObjectProperty(name, properties = {}) { return this.addProperty(name, { type: 'object', properties }); } required(fields) { this.schema.required = Array.isArray(fields) ? fields : [fields]; return this; } addRequired(field) { if (!this.schema.required) { this.schema.required = []; } if (!this.schema.required.includes(field)) { this.schema.required.push(field); } return this; } description(desc) { this.schema.description = desc; return this; } enum(values) { this.schema.enum = values; return this; } minimum(min) { this.schema.minimum = min; return this; } maximum(max) { this.schema.maximum = max; return this; } minLength(min) { this.schema.minLength = min; return this; } maxLength(max) { this.schema.maxLength = max; return this; } minItems(min) { this.schema.minItems = min; return this; } maxItems(max) { this.schema.maxItems = max; return this; } build() { return { ...this.schema }; } static create() { return new SchemaBuilder(); } static arrayOf(itemType) { if (typeof itemType === 'string') { return new SchemaBuilder().array({ type: itemType }); } return new SchemaBuilder().array(itemType); } static objectWith(properties) { return new SchemaBuilder().object(properties); } } module.exports = SchemaBuilder;