rawmodel / framework

Strongly-typed JavaScript object with support for validation and error handling.
https://rawmodel.github.io/framework/
MIT License
142 stars 16 forks source link

JSON Schema support #56

Closed xpepermint closed 5 years ago

xpepermint commented 5 years ago

RawModel should provide its own schema structure which follows and can be created from JSON Schema. A schema in RawModel are basically arrays of property definitions.

export interface Schema {
  title: string;
  description?: string;
  config?: SchemaConfig;
  props: SchemaProp[];
}
export interface SchemaConfig {
  failFast?: boolean;
}
export interface SchemaProp {
  title: string;
  cast?: PropCast;
  defaultValue?: any;
  fakeValue?: any;
  emptyValue?: any;
  validate?: ValidatorRecipe[];
  populatable?: string[];
  serializable?: string[];
}
export interface PropCast {
  array: boolean;
  handler: 'String' | 'Boolean' | 'Integer' | 'Float' | 'Number' | 'Date' | Schema;
}

The new interface should look like this:

export function parseJsonSchema(json) {
    ...
}
export function createModelClass(json: Schema) {
    const Model = eval(`class ${json.title} extends Model {}`);
    json.properties.forEach((prop) => {
        Model.addProp(prop);
    });
    return Model;    
}
import { parseJsonSchema, createModelClass } from '@rawmodel/schema';

// Parse JSON schema into RawModel Schema.
const schema = parseJsonSchema({ ...JSON_SCHEMA... });

// Create a new Model class object.
const User = createModelClass(schema);

Refs: https://github.com/rawmodel/framework/issues/24, https://github.com/rawmodel/framework/issues/15

xpepermint commented 5 years ago

Implemented in https://github.com/rawmodel/framework/pull/62.