Skip to content

Instantly share code, notes, and snippets.

@anoopsinghbayes
Forked from yoadsn/mt.js
Created July 9, 2018 21:29
Show Gist options
  • Save anoopsinghbayes/b9c3d4493662028d20b3e93954bb1ec4 to your computer and use it in GitHub Desktop.
Save anoopsinghbayes/b9c3d4493662028d20b3e93954bb1ec4 to your computer and use it in GitHub Desktop.
GQL - Multi Tenant Idea
const tenantsConfig = [
{ name: 't1', connStr: 'mongodb://...' },
{ name: 't2', connStr: 'mongodb://...' }
];
let tenantConns = tenantsConfig.map(tenant => ({
...tenant,
conn: mongoose.createConnection(tenant.connStr))
});
let tenantModels = tenantConns.map(tenant => ({
...tenant,
models: createModels(tenant.conn) // see below
}));
let tenantGqlSchemas = tenantModels.map(tenant => ({
...tenant,
gqlSchema: createGQLSchema(tenant.models) // see below
})).reduce((map, tenant) => {
return {
...map,
[tenant.name]: tenant.gqlSchema
}
}, {});
// When setting up the GQL api endpint (Assuming express-graphql)
app.use('/graphql', graphqlHTTP(req => ({
schema: tenantGqlSchemas[getTenantNameFromRequest(req)].gqlSchema,
graphiql: process.env.NODE_ENV !== 'production',
pretty: process.env.NODE_ENV !== 'production',
})));
// Somewhere else
import { ComposeStorage } from 'graphql-compose';
import composeWithMongoose from 'graphql-compose-mongoose';
import { composeWithRelay } from 'graphql-compose-relay';
import UserSchema from './Schemas/User';
import DogSchema from './Schemas/Dog';
const createModels = (conn) => {
let UserModel = conn.model('User', UserSchema);
let DogModel = conn.model('Dog', DogSchema);
return {
user: UserModel,
dog: DogModel
}
}
const createGQLSchema = (models) => {
const GQC = new ComposeStorage(); // Don't want to reuse the GQC storage - this allows creating a new one.
const userTC = composeWithRelay(composeWithMongoose(models.user));
const dogTC = composeWithRelay(composeWithMongoose(models.dog));
return GQC.rootQuery().addFields({
user: userTC.get('$findById'),
dog: dogTC.get('$findById')
//... more
}).buildSchema();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment