Vincit / objection-graphql

GraphQL schema generator for objection.js
MIT License
307 stars 34 forks source link

Optimal usage of the db schema name in GraphQL schema #26

Closed nasushkov closed 6 years ago

nasushkov commented 6 years ago

A few days ago I switched to a named schema for my DB tables. So right now I ended up with prefixing all table references in my models with the DB schema name. However, I don't want my GraphQL schema to be prefixed with the DB schema name. Is there any workaround for this case?

koskimas commented 6 years ago

Maybe you could use withSchema method instead of prefixing your table names:

  graphql(graphQlSchema, req.query.graph, {
    onQuery(builder) {
      builder.withSchema('yourSchema');
    }
  })
koskimas commented 6 years ago

Actually nowadays objection-graphql could use the model name instead of table name to generate the api names since ES6 classes are a requirement. I don't think anyone writes classes without names.

koskimas commented 6 years ago

@nasushkov If you have multiple schemas, maybe you can use this workaround:

function makeSchemaQueryBuilder(schema) {
  return class extends Model.QueryBuilder {
    constructor(..args) {
      super(...args);
      this.withSchema(schema);
    }
  };
}

class Foo extends Model {
  static QueryBuilder = makeSchemaQueryBuilder('schema1');
}

class Bar extends Model {
  static QueryBuilder = makeSchemaQueryBuilder('schema2');
}

I'll change objection-graphql to use the model name instead of table name to create schema names.

nasushkov commented 6 years ago

@koskimas Thanks for all your tips. My temp solution was overriding getTableName in the base class (I used two base classes for each schema):

export default class BaseModel extends Model {
    static dbSchemaName = 'myschema'
    static getTableName(){
        const tableName = super.getTableName()
        return `${this.dbSchemaName}.${tableName}`
    }
}

Then I just set the tableName without prefix.

export default class Company extends BaseModel {
    static tableName = 'company'
}

Although that workaround worked for me, it seems that it's tightly coupled with the current internal implementation, so I'd better go with your solution.

zpartal commented 6 years ago

@koskimas

I'll change objection-graphql to use the model name instead of table name to create schema names.

Was this change ever made? I'm running into the same issue and have solved it for now using the approach you gave here.