forked from zapkub/typescript-apollo-nap-mongo-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
125 lines (116 loc) · 3.88 KB
/
Copy pathserver.ts
File metadata and controls
125 lines (116 loc) · 3.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import * as express from 'express'
import * as bearerToken from 'express-bearer-token'
import * as fs from 'fs'
import * as bodyParser from 'body-parser'
import chalk from 'chalk'
import { Connection, Model } from 'mongoose'
import { graphiqlExpress, graphqlExpress } from 'apollo-server-express'
import * as next from 'next'
import clientRoutes from './routes'
import { createGraphQLSchema } from './graphql'
import createConnectors, { GQConnectors } from './connectors'
import config from './config';
import { jwtSessionMiddleware } from 'jamplay-service-utility'
const cors = require('cors')
declare global {
interface ApplicationLogger {
log: (message: string) => void
}
interface SVContext {
server?: express.Application
config: ApplicationConfig
logger: ApplicationLogger
__connection: Connection
}
interface GQResolverContext extends SVContext, express.Request {
models: GQApplicationModels
connectors: GQConnectors
token: string
// user: GBUserType
userId?: string
}
}
export default async function init(context: SVContext) {
let server = context.server
if (!server) {
server = express()
}
console.log(chalk.greenBright(context.config.dev ? 'Run app in dev mode' : 'Run app in prod mode'))
const { schema, models } = createGraphQLSchema(context)
const connectors = createConnectors({ napEndpoint: context.config.NAP_URI, models, logger: context.logger })
server.use(cors())
server.use(bodyParser.json())
server.use(bearerToken())
server.use('/graphql', async (req, res, next) => {
const mockRes = ({
status: () => ({
send: () => ({})
})
})
const q = jwtSessionMiddleware({ secret: context.config.JWT_SECRET }).map((item) => item(req, mockRes, () => { }))
await Promise.all(q)
console.log(( req as any ).user)
next()
})
server.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql' }))
server.use('/graphql', graphqlExpress(async (req) => ({
schema,
context: {
...req,
...context,
models,
connectors,
}
})))
return {
server,
start: async () => {
server.use(require('express-ping').ping())
if (config.dev) {
const clientApp = next({ dev: context.config.dev })
const clientRoutesHandler = clientRoutes.getRequestHandler(clientApp)
server.use(clientRoutesHandler)
await clientApp.prepare()
}
server.listen(context.config.PORT, async () => {
context.logger.log(chalk.bgGreen(`Start application !!`))
context.logger.log(chalk.green(`Application start on port =>> ${context.config.PORT}`))
// Create fragment matcher
// await fetch(`http://localhost:${context.config.PORT}/graphql`, {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json'
// },
// body: JSON.stringify({
// query: ` {
// __schema {
// types {
// kind
// name
// possibleTypes {
// name
// }
// }
// }
// }
// `,
// }),
// })
// .then((result) => result.json())
// .then((result) => {
// // here we're filtering out any type information unrelated to unions or interfaces
// const filteredData = result.data.__schema.types.filter(
// (type) => type.possibleTypes !== null,
// );
// result.data.__schema.types = filteredData;
// fs.writeFile('./static/fragmentTypes.json', JSON.stringify(result.data), (err) => {
// if (err) {
// console.error('Error writing fragmentTypes file', err);
// }
// console.log('Fragment types successfully extracted!');
// });
// });
})
}
}
}