The project stack is made up of nodejs, graphql yoga and mongodb and I am trying to build it to heroku. The build works perfectly locally but the issue though is that on heroku the build is successful but it immediately crashes when I open it up.
Here is the index.js file:
const {execute, ExecutionArgs, subscribe} = require('graphql');
const {makeBehavior} = require('graphql-ws/lib/use/uWebSockets');
const {createSchema, createYoga, Repeater, createPubSub} = require('graphql-yoga');
const {App, HttpRequest, HttpResponse} = require('uWebSockets.js');
const typeDefs = require('./src/schema');
const resolvers = require('./src/resolvers/index');
const models = require('./src/models/index');
const {decode} = require('next-auth/jwt');
const {connect} = require('./src/db');
const {useResponseCache} = require("@graphql-yoga/plugin-response-cache");
const {useDeferStream} = require("@graphql-yoga/plugin-defer-stream");
// Connect to MongoDB
connect(process.env.DB_HOST).then(() => {
console.log("Connected to MongoDB!");
console.log(process.env.PORT, process.env.NODE_ENV)
}).catch(e => {
console.error(e);
console.log('MongoDB connection error. Please make sure MongoDB is running.');
process.exit();
});
const pubSub = createPubSub()
const yoga = createYoga({
cors: {
origin: '*',
methods: ['GET', 'POST'],
allowedHeaders: ['Content-Type', 'Authorization'],
},
schema: createSchema({
typeDefs: typeDefs,
resolvers: resolvers,
}),
plugins: [
useDeferStream(),
],
context: async ({ request: req}) => {
let token = req?.headers?.get('authorization')?.split(' ')[1] || (req?.headers?.get("authorization"))
// let token = req?.headers?.get('authorization')?.split(' ')[1];
//check if introspection query
if (req?.body?.query?.includes("IntrospectionQuery")) {
return {
models,
user: null,
};
}
const start = Date.now();
try {
const jwtPayload = await decode({
token: token,
secret: process.env.NEXTAUTH_SECRET,
});
// console.log("jwtPayload", jwtPayload)
const mid = new Date().getTime();
const user = await models.User.findOne({email: jwtPayload?.email}, {
_id: 1,
email: 1,
preferences: 1,
accountType: 1,
});
const end = new Date().getTime();
const duration = end - start;
// console.log(`Request took: ${duration}ms`, end - mid);
return {
pubSub,
user,
models,
};
} catch (e) {
console.log(e);
return {
models,
user: null,
};
}
},
graphiql: {
subscriptionsProtocol: 'WS', // use WebSockets instead of SSE
},
});
// yoga's envelop may augment the `execute` and `subscribe` operations
// so we need to make sure we always use the freshest instance
const wsHandler = makeBehavior({
execute: args => (args).rootValue.execute(args),
subscribe: args => (args).rootValue.subscribe(args),
onSubscribe: async (ctx, msg) => {
const {schema, execute, subscribe, contextFactory, parse, validate} = yoga.getEnveloped(ctx);
const args = {
schema,
operationName: msg.payload.operationName,
document: parse(msg.payload.query),
variableValues: msg.payload.variables,
contextValue: await contextFactory(),
rootValue: {
execute,
subscribe,
},
};
const errors = validate(args.schema, args.document);
if (errors.length) return errors;
return args;
},
});
const port = process.env.NODE_ENV === 'production' ? process.env.PORT : 8080;
console.log('PORT:', process.env.PORT);
App()
.any('/*', yoga)
.ws(yoga.graphqlEndpoint, wsHandler)
.listen(port, (token) => {
if (token) {
console.log(`Server is running on port ${port}`);
} else {
console.error('Failed to start server');
}
});
// Handle graceful shutdown
process.on('SIGTERM', () => {
console.log('SIGTERM signal received. Shutting down gracefully.');
// Perform any necessary cleanup here
process.exit(0);
});
// export const app = App().any('/*', yoga).ws(yoga.graphqlEndpoint, wsHandler);
I believe there is some issue with the App() function at the bottom and the port which in the env is set to development locally and production in heroku.
Austin Edelman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.