Created
October 13, 2023 12:32
-
-
Save umutyerebakmaz/2ab533fb6e6b064b732dad0a7ad7911e to your computer and use it in GitHub Desktop.
yoga-express-middleware.example.ts
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
#!/usr/bin / env node | |
import express from 'express'; | |
import cors from 'cors'; | |
import bodyParser from 'body-parser'; | |
import '@lib/env'; | |
import { authChecker } from './auth-checker'; | |
import environmentErrorReporter from '@lib/environmentErrorReporter'; | |
import { appDataSource } from '@server/datasource'; | |
import { buildSchema } from 'type-graphql'; | |
import { resolvers } from './modules/resolvers'; | |
import { tokenMiddleware } from '../middleware/token.middleware'; | |
import { createYoga } from 'graphql-yoga'; | |
const env = process.env; | |
import { context } from './context'; | |
import { graphqlUploadExpress } from 'graphql-upload-ts'; | |
const startServer = async () => { | |
environmentErrorReporter.report(new Error()); | |
console.time('main'); | |
console.log(`current environment: ${env.NODE_ENV}`); | |
// TypeORM DataSource | |
await appDataSource.initialize(); | |
// Express Server | |
const app = express(); | |
// TypeGraphQL Schema Builder | |
const schema = await buildSchema({ | |
resolvers, | |
authChecker, | |
}); | |
// GraphQL Yoga | |
const yoga = createYoga({ | |
schema, | |
context, | |
graphiql: process.env.NODE_ENV === 'production' ? false : true, | |
}); | |
// Middlewares of Express | |
app.use( | |
cors({ | |
origin: (_requestOrigin, callback) => callback(null, true), | |
}), | |
bodyParser.json({ limit: '100mb' }), | |
bodyParser.urlencoded({ limit: '50mb', extended: true }), | |
express.static('public') | |
); | |
app.use(graphqlUploadExpress()); | |
app.use('/graphql', (req, res, next) => tokenMiddleware(req, res, next)); | |
app.use('/graphql', (req, res) => yoga(req, res)); | |
// Listener of Express | |
app.listen(env.SERVER_PORT, () => { | |
console.info(`# app server listening at http://localhost:${env.SERVER_PORT}/graphql`); | |
console.timeEnd('main'); | |
console.log(`${env.NODE_ENV} server`); | |
}); | |
}; | |
// Initialize server | |
startServer().catch(err => { | |
console.error(err); | |
process.exit(1); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment