chore: Integrate graphql to the express app
This commit is contained in:
@@ -1,10 +1,12 @@
|
||||
import appConfig from './config/app'
|
||||
import createError from 'http-errors';
|
||||
import express, { Request, Response, NextFunction } from 'express';
|
||||
import { graphqlHTTP } from 'express-graphql';
|
||||
import logger from './helpers/logger';
|
||||
import morgan from './helpers/morgan';
|
||||
|
||||
import indexRouter from './routes/index';
|
||||
import rootResolver from './graphql/root-resolver'
|
||||
import graphQLSchema from './graphql/graphql-schema'
|
||||
|
||||
const app = express();
|
||||
const port = appConfig.port;
|
||||
@@ -13,7 +15,14 @@ app.use(morgan);
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: false }));
|
||||
|
||||
app.use('/', indexRouter);
|
||||
app.use(
|
||||
'/graphql',
|
||||
graphqlHTTP({
|
||||
schema: graphQLSchema,
|
||||
rootValue: rootResolver,
|
||||
graphiql: true,
|
||||
}),
|
||||
);
|
||||
|
||||
// catch 404 and forward to error handler
|
||||
app.use(function(req: Request, res: Response, next: NextFunction) {
|
||||
|
9
packages/backend/src/graphql/graphql-schema.ts
Normal file
9
packages/backend/src/graphql/graphql-schema.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { buildSchema } from 'graphql';
|
||||
|
||||
const graphQLSchema = buildSchema(`
|
||||
type Query {
|
||||
hello: String
|
||||
}
|
||||
`);
|
||||
|
||||
export default graphQLSchema;
|
7
packages/backend/src/graphql/root-resolver.ts
Normal file
7
packages/backend/src/graphql/root-resolver.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
const rootResolver = {
|
||||
hello: () => {
|
||||
return 'Hello world!';
|
||||
},
|
||||
};
|
||||
|
||||
export default rootResolver;
|
@@ -1,13 +1,19 @@
|
||||
import morgan, { StreamOptions } from 'morgan';
|
||||
|
||||
import { Request } from 'express';
|
||||
import logger from './logger';
|
||||
|
||||
const stream: StreamOptions = {
|
||||
write: (message) => logger.http(message.substring(0, message.lastIndexOf('\n')))
|
||||
write: (message) => logger.http(message.substring(0, message.lastIndexOf("\n")))
|
||||
};
|
||||
|
||||
const registerGraphQLToken = () => {
|
||||
morgan.token("graphql-query", (req: Request) => `GraphQL ${req.body.query}`);
|
||||
};
|
||||
|
||||
registerGraphQLToken();
|
||||
|
||||
const morganMiddleware = morgan(
|
||||
":method :url :status :res[content-length] - :response-time ms",
|
||||
":method :url :status :res[content-length] - :response-time ms\n:graphql-query",
|
||||
{ stream }
|
||||
);
|
||||
|
||||
|
@@ -1,7 +0,0 @@
|
||||
import { Request, Response } from 'express';
|
||||
|
||||
const indexRouter = (_request: Request, response: Response) => {
|
||||
return response.json({ hello: 'world!' })
|
||||
};
|
||||
|
||||
export default indexRouter;
|
Reference in New Issue
Block a user