-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
66 lines (62 loc) · 1.9 KB
/
index.js
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
require('dotenv').config()
const { ApolloServer } = require('apollo-server')
const schema = require('./schema')
const resolvers = require('./resolvers')
const MicrosubAPI = require('./datasources/microsub')
const MicropubAPI = require('./datasources/micropub')
const IndieAuthAPI = require('./datasources/indieauth')
const MongoAPI = require('./datasources/mongo')
const users = new MongoAPI()
// set up any dataSources our resolvers need
const dataSources = () => ({
microsub: new MicrosubAPI(),
micropub: new MicropubAPI(),
indieauth: new IndieAuthAPI(),
mongo: users,
})
const context = async ({ req, connection }) => {
// simple auth check on every request
if (connection) {
// check connection for metadata
return connection.context
} else {
try {
const auth = (req.headers && req.headers.authorization) || ''
const user = await users.findOrCreateUser(auth)
return { user }
} catch (err) {
return { user: {} }
}
}
}
const server = new ApolloServer({
typeDefs: schema,
dataSources,
resolvers,
context,
cors: {
origin: new URL(process.env.URL).origin,
},
resolverValidationOptions: {
requireResolversForResolveType: false,
},
subscriptions: {
onConnect: async (connectionParams, webSocket) => {
try {
const auth = (connectionParams && connectionParams.authToken) || ''
const user = await users.findOrCreateUser(auth)
console.log('[websocket connect]', user.url)
return { user }
} catch (err) {
return { user: {} }
}
},
// onDisconnect: (webSocket, context) => {
// console.log('Socket disconnect')
// },
},
})
server.listen(process.env.PORT || 4000).then(({ url, subscriptionsUrl }) => {
console.log(`🚀 Server ready at ${url}`)
console.log(`🚀 Subscriptions ready at ${subscriptionsUrl}`)
})