chore: Extract error handler and graphql instance to seperate files
This commit is contained in:
@@ -3,12 +3,10 @@ import createError from 'http-errors';
|
||||
import express, { Request, Response, NextFunction } from 'express';
|
||||
import cors from 'cors';
|
||||
import corsOptions from './config/cors-options';
|
||||
import { graphqlHTTP } from 'express-graphql';
|
||||
import graphQLInstance from './helpers/graphql-instance';
|
||||
import logger from './helpers/logger';
|
||||
import morgan from './helpers/morgan';
|
||||
|
||||
import rootResolver from './graphql/root-resolver'
|
||||
import graphQLSchema from './graphql/graphql-schema'
|
||||
import errorHandler from './helpers/error-handler'
|
||||
|
||||
const app = express();
|
||||
const port = appConfig.port;
|
||||
@@ -16,32 +14,15 @@ const port = appConfig.port;
|
||||
app.use(morgan);
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: false }));
|
||||
|
||||
app.use(cors(corsOptions))
|
||||
|
||||
app.use(
|
||||
'/graphql',
|
||||
graphqlHTTP({
|
||||
schema: graphQLSchema,
|
||||
rootValue: rootResolver,
|
||||
graphiql: true,
|
||||
}),
|
||||
);
|
||||
app.use('/graphql', graphQLInstance);
|
||||
|
||||
// catch 404 and forward to error handler
|
||||
app.use(function(req: Request, res: Response, next: NextFunction) {
|
||||
next(createError(404));
|
||||
});
|
||||
|
||||
// error handler
|
||||
app.use(function(err: any, req: Request, res: Response, _next: NextFunction) {
|
||||
if(err.message === 'Not Found') {
|
||||
res.status(404).end()
|
||||
} else {
|
||||
logger.error(err.message)
|
||||
res.status(500).end()
|
||||
}
|
||||
});
|
||||
app.use(errorHandler);
|
||||
|
||||
app.listen(port, () => {
|
||||
logger.info(`Server is listening on ${port}`)
|
||||
|
13
packages/backend/src/helpers/error-handler.ts
Normal file
13
packages/backend/src/helpers/error-handler.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import logger from './logger';
|
||||
|
||||
const errorHandler = (err: any, req: Request, res: Response, _next: NextFunction) => {
|
||||
if(err.message === 'Not Found') {
|
||||
res.status(404).end()
|
||||
} else {
|
||||
logger.error(err.message)
|
||||
res.status(500).end()
|
||||
}
|
||||
}
|
||||
|
||||
export default errorHandler;
|
11
packages/backend/src/helpers/graphql-instance.ts
Normal file
11
packages/backend/src/helpers/graphql-instance.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { graphqlHTTP } from 'express-graphql';
|
||||
import rootResolver from '../graphql/root-resolver'
|
||||
import graphQLSchema from '../graphql/graphql-schema'
|
||||
|
||||
const graphQLInstance = graphqlHTTP({
|
||||
schema: graphQLSchema,
|
||||
rootValue: rootResolver,
|
||||
graphiql: true,
|
||||
})
|
||||
|
||||
export default graphQLInstance;
|
Reference in New Issue
Block a user