Last active
July 9, 2018 21:29
-
-
Save yoadsn/44c68bb55d1fb56cfd9baea6cb740880 to your computer and use it in GitHub Desktop.
GQL - Multi Tenant Idea
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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