Skip to content

Instantly share code, notes, and snippets.

@pfulop
Last active September 18, 2016 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pfulop/0a0f9d5de007bd38e4e314e726ea1be1 to your computer and use it in GitHub Desktop.
Save pfulop/0a0f9d5de007bd38e4e314e726ea1be1 to your computer and use it in GitHub Desktop.
import { Model} from 'objection';
export default class RootModel extends Model {
static get generateGraphSchema(){
const required = {}, relations = {},convertType = (type) => {
switch (type) {
case 'string': return 'String';
case 'integer': return 'Int';
case 'number': return 'Float';
case 'boolean': return 'Boolean';
default: return 'i will throw error';
}
};
let typeDef = `type ${this.name} {`;
Object.keys(this.jsonSchema.required).forEach(k=>required[this.jsonSchema.required[k]]=true);
Object.keys(this.relationMappings).forEach(k=>{
let relation = this.relationMappings[k];
if(relation.relation === this.HasManyRelation || relation.relation === this.ManyToManyRelation)
relations[k]=`[${relation.modelClass.name}]`;
else
relations[k]=`${relation.modelClass.name}`;
});
Object.keys(this.jsonSchema.properties).forEach(k=>{
if (!relations.hasOwnProperty(k)) {
let type = this.jsonSchema.properties[k].type;
if(k==='id')
typeDef+=`${k}: ID!`;
else
typeDef+=`${k}: ${convertType(type)}`;
if(required.hasOwnProperty(k))
typeDef+='!';
typeDef+=' ';
}
});
Object.keys(relations).forEach(k=>{
typeDef+=`${k}: ${relations[k]}`;
if(required.hasOwnProperty(k) || required.hasOwnProperty(k+'Id'))
typeDef+='!';
typeDef+=' ';
});
typeDef+='}';
return typeDef;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment