Created
September 27, 2019 18:20
-
-
Save Stradivario/45e558d50450d89de3eba12207068cc1 to your computer and use it in GitHub Desktop.
Graphql Gateway for @gapi applications
This file contains 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
import { | |
Module, | |
CoreModule, | |
Bootstrap, | |
ON_REQUEST_HANDLER, | |
GRAPHQL_PLUGIN_CONFIG, | |
Container | |
} from '@gapi/core'; | |
import { | |
MicroserviceModule, | |
AFTER_MIDDLEWARE, | |
BEFORE_MIDDLEWARE, | |
MiddlewareOptions, | |
ProxyService | |
} from '@rxdi/graph-gateway'; | |
import { ResponseToolkit } from 'hapi'; | |
import { promisify } from 'util'; | |
import { load, safeLoad } from 'js-yaml'; | |
import { readFile, readFileSync, stat, statSync } from 'fs'; | |
const fileName = './gateway.yml'; | |
let temp = statSync(fileName).mtime.toISOString(); | |
async function loadYml() { | |
return load(await promisify(readFile)(fileName, { encoding: 'utf-8' })); | |
} | |
function safeLoadYml() { | |
return safeLoad(readFileSync(fileName, { encoding: 'utf-8' })); | |
} | |
@Module({ | |
providers: [ | |
{ | |
provide: ON_REQUEST_HANDLER, | |
deps: [GRAPHQL_PLUGIN_CONFIG], | |
useFactory: (config: GRAPHQL_PLUGIN_CONFIG) => async ( | |
next, | |
request: Request, | |
h: ResponseToolkit, | |
err: Error | |
) => { | |
config.graphqlOptions.context = config.graphqlOptions.context || {}; | |
config.graphqlOptions.context['headers'] = request.headers; | |
const stats = await promisify(stat)(fileName); | |
if (new Date(temp).toISOString() !== stats.mtime.toISOString()) { | |
config.graphqlOptions.schema = await Container.get( | |
ProxyService | |
).getSchemaIntrospection((await loadYml()).services); | |
temp = stats.mtime.toISOString(); | |
console.log('Configuration has changed...'); | |
} | |
return next(); | |
} | |
}, | |
{ | |
provide: BEFORE_MIDDLEWARE, | |
useFactory: () => (options: MiddlewareOptions) => { | |
return options; | |
} | |
}, | |
{ | |
provide: AFTER_MIDDLEWARE, | |
useFactory: () => (res, options: MiddlewareOptions) => { | |
if (res.statusCode && res.statusCode !== 200) { | |
throw new Error('Unauthorized'); | |
} | |
return res; | |
} | |
} | |
], | |
imports: [ | |
MicroserviceModule.forRoot(safeLoadYml().services), | |
CoreModule.forRoot({ | |
server: { | |
hapi: { | |
port: 9003 | |
} | |
}, | |
graphql: { | |
path: '/graphql', | |
openBrowser: false, | |
initQuery: false, | |
graphiQlPlayground: true, | |
graphiQlPath: '/graphiql', | |
watcherPort: 8999, | |
graphqlOptions: { | |
tracing: true, | |
schema: null | |
} | |
} | |
}) | |
] | |
}) | |
export class AppModule {} | |
Bootstrap(AppModule).subscribe(() => console.log('Started')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment