From 37fe337d007513d81094f0767e70471620bd2194 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lio=20A=2E=20Heckert?= Date: Sat, 21 Jul 2018 19:26:35 -0300 Subject: [PATCH] Get singular and plural model names from jsonSchema This is similar to `listFieldName` and `fieldName` from `graphQLBuilder().model()`'s extra parameter. It can simple replace `listFieldName` and `fieldName` if you can add `collectiveName` and `singleName` to your models's jsonSchema. The benefit is: * Center the model description; * Produce the correct single type name in the result graphQL schema; * Share the model identification with oder modules in the app. --- lib/SchemaBuilder.js | 5 +++-- lib/utils.js | 4 +++- tests/integration.js | 30 ++++++++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/lib/SchemaBuilder.js b/lib/SchemaBuilder.js index 5b50a71..ece9978 100644 --- a/lib/SchemaBuilder.js +++ b/lib/SchemaBuilder.js @@ -131,8 +131,9 @@ class SchemaBuilder { _.forOwn(this.models, (modelData) => { const defaultFieldName = fieldNameForModel(modelData.modelClass); - const singleFieldName = modelData.opt.fieldName || defaultFieldName; - const listFieldName = modelData.opt.listFieldName || (`${defaultFieldName}s`); + const schema = modelData.modelClass.jsonSchema; + const singleFieldName = schema.singleName || modelData.opt.fieldName || defaultFieldName; + const listFieldName = schema.collectiveName || modelData.opt.listFieldName || (`${defaultFieldName}s`); fields[singleFieldName] = this._rootSingleField(modelData); fields[listFieldName] = this._rootListField(modelData); diff --git a/lib/utils.js b/lib/utils.js index cbc30e8..2798c4b 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -8,7 +8,9 @@ function isExcluded(opt, prop) { } function typeNameForModel(modelClass) { - return _.upperFirst(_.camelCase(modelClass.tableName)); + const schema = modelClass.jsonSchema; + const name = schema.singleName || schema.title || modelClass.tableName; + return _.upperFirst(_.camelCase(name)); } module.exports = { diff --git a/tests/integration.js b/tests/integration.js index b75c2fc..a867a6f 100644 --- a/tests/integration.js +++ b/tests/integration.js @@ -1281,4 +1281,34 @@ describe('integration tests', () => { }); })); }); + + describe('get singular and plural names from jsonSchema', () => { + let schema; + + before(() => { + const { Model } = require('objection'); + class Human extends Model { + static get tableName() { return 'humans' } + static get jsonSchema() { + return { + type: 'object', + singleName: 'person', + collectiveName: 'mankind', + properties: { id: { type: 'integer' }} + } + } + } + schema = mainModule + .builder() + .model(Human) + .build(); + }); + + it('has a correct type name', () => { + const fields = schema._queryType._fields + expect(fields.person.type).to.be.a(GraphQLObjectType); + expect(fields.mankind.type).to.be.a(GraphQLList); + }); + }); + });