Skip to content

Instantly share code, notes, and snippets.

@Lucas-Geitner
Created July 2, 2020 06:57
Show Gist options
  • Save Lucas-Geitner/85594da61a20d20a546c3ad975229a78 to your computer and use it in GitHub Desktop.
Save Lucas-Geitner/85594da61a20d20a546c3ad975229a78 to your computer and use it in GitHub Desktop.
const {
ApolloServer,
} = require('apollo-server-express')
const express = require('express')
const app = express()
const {typeDefs} = require('./schema/TypeDefs')
const { PubSub } = require('apollo-server')
const cookieParser = require('cookie-parser')
const { GraphQLScalarType } = require('graphql')
const { Kind } = require('graphql/language')
const Mutation = require('./schema/Mutation')
const Query = require('./schema/Query')
require('./models/User.js')
require('./models/Comite.js')
require('./models/UGC.js')
require('./models/Comment.js')
require('./models/Page.js')
require('./models/Cotisation')
require('./models/Donation')
const mongoose = require('mongoose')
const User = mongoose.model( 'User' )
const jwt = require('jsonwebtoken')
const http = require('http')
var cors = require('cors')
const USER_CONFIRMATION = 'USER_CONFIRMATION'
function createServer() {
const server = new ApolloServer({
typeDefs,
context: req => ({ ...req, }),
resolvers:{
Mutation,
Query,
Date: new GraphQLScalarType({
name: 'Date',
description: 'An ISO 8601 formatted date',
parseValue (value) {
return new Date(value)
},
parseLiteral (astValue) {
if (astValue.kind === Kind.STRING || astValue === Kind.INT) {
return new Date(astValue)
}
return null
},
serialize (value) {
return value.toISOString()
}
}),
OrganizerType: {
USER: 'User',
COMMITTEE: 'Comite'
}
},
formatError: error => {
console.dir(error)
return error
},
})
const whitelist = [ 'http://localhost:7777', 'localhost:7777', 'dev.generation-s.fr', 'https://dev.generation-s.fr', 'https://*.generation-s.fr']
const corsOptions = { origin(origin, callback){ const originIsWhitelisted = whitelist.indexOf(origin) !== -1; callback(null, originIsWhitelisted) }, credentials: true }
app.use(cookieParser())
app.use(cors(corsOptions))
app.use((req, res, next) => {
let sslUrl;
if (process.env.NODE_ENV === 'production' && req.headers['x-forwarded-proto'] !== 'https') {
sslUrl = ['https://xxx', req.url].join('');
return res.redirect(sslUrl);
}
return next();
}); // force HTTPPPS.
// decode the JWT so we can get the user Id on each request
app.use((req, res, next) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8')
const { token } = req.cookies
if (token) {
const { userId } = jwt.verify(token, process.env.COOKIE_SECRET )
// put the userId onto the req for future requests to access
req.userId = userId
}
next()
})
// 2. Create a middleware that populates the user on each request
app.use(async (req, res, next) => {
// if they aren't logged in, skip this
if (!req.userId) return next()
const user = await User.find({id: req.userId})
req.user = user
next()
})
server.applyMiddleware({
app,
cors: corsOptions
}) // app is from an existing express app
const httpServer = http.createServer(app)
server.installSubscriptionHandlers(httpServer)
app.get('/', (req, res) => {
res.redirect('xxx')
})
app.use('/static', express.static(__dirname + '/public'))
app.use(require('forest-express-mongoose').init({
modelsDir: __dirname + '/models',
envSecret: process.env.FOREST_ENV_SECRET,
authSecret: process.env.FOREST_AUTH_SECRET,
mongoose
}))
const port = process.env.PORT || 3000
httpServer.listen(port, () => {
console.log(`๐Ÿš€ Server ready at http://localhost:${port}${server.graphqlPath}`)
console.log(`๐Ÿš€ Subscriptions ready at ws://localhost:${port}${server.subscriptionsPath}`)
})
}
module.exports = createServer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment