stacker.news/pages/api/graphql.js

79 lines
2.6 KiB
JavaScript
Raw Normal View History

import { ApolloServer } from '@apollo/server'
import { startServerAndCreateNextHandler } from '@as-integrations/next'
import resolvers from '@/api/resolvers'
import models from '@/api/models'
import lnd from '@/api/lnd'
import typeDefs from '@/api/typeDefs'
import { getServerSession } from 'next-auth/next'
import { getAuthOptions } from './auth/[...nextauth]'
import search from '@/api/search'
2023-11-21 22:46:03 +00:00
import {
ApolloServerPluginLandingPageLocalDefault,
ApolloServerPluginLandingPageProductionDefault
} from '@apollo/server/plugin/landingPage/default'
2021-03-25 19:29:24 +00:00
2022-04-27 22:06:42 +00:00
const apolloServer = new ApolloServer({
2021-03-25 19:29:24 +00:00
typeDefs,
resolvers,
2023-11-22 15:16:40 +00:00
introspection: true,
2022-04-28 18:11:05 +00:00
plugins: [{
requestDidStart (initialRequestContext) {
return {
2023-07-27 00:18:42 +00:00
executionDidStart () {
2022-04-28 18:11:05 +00:00
return {
willResolveField ({ source, args, context, info }) {
const start = process.hrtime.bigint()
return (error, result) => {
const end = process.hrtime.bigint()
const ms = (end - start) / 1000000n
2023-07-31 21:02:50 +00:00
if (ms > 50) {
2022-04-28 18:11:05 +00:00
console.log(`Field ${info.parentType.name}.${info.fieldName} took ${ms}ms`)
}
if (error) {
console.log(`Field ${info.parentType.name}.${info.fieldName} failed with ${error}`)
2022-04-28 18:11:05 +00:00
}
}
2023-07-27 00:18:42 +00:00
},
async executionDidEnd (err) {
if (err) {
console.error('hey bud', err)
}
2022-04-28 18:11:05 +00:00
}
}
}
}
}
2023-11-21 22:46:03 +00:00
},
process.env.NODE_ENV === 'production'
? ApolloServerPluginLandingPageProductionDefault(
{ embed: { endpointIsEditable: false, persistExplorerState: true, displayOptions: { theme: 'dark' } }, footer: false })
: ApolloServerPluginLandingPageLocalDefault(
{ embed: { endpointIsEditable: false, persistExplorerState: true, displayOptions: { theme: 'dark' } }, footer: false })]
})
export default startServerAndCreateNextHandler(apolloServer, {
context: async (req, res) => {
const apiKey = req.headers['x-api-key']
let session
if (apiKey) {
const sessionFieldSelect = { name: true, id: true, email: true }
const user = await models.user.findUnique({ where: { apiKey }, select: { ...sessionFieldSelect, apiKeyEnabled: true } })
if (user?.apiKeyEnabled) {
const { apiKeyEnabled, ...sessionFields } = user
session = { user: { ...sessionFields, apiKey: true } }
}
} else {
session = await getServerSession(req, res, getAuthOptions(req))
}
2021-04-12 18:05:09 +00:00
return {
models,
2023-12-14 17:30:51 +00:00
headers: req.headers,
2021-04-29 21:58:43 +00:00
lnd,
2022-04-21 22:50:02 +00:00
me: session
? session.user
2022-04-21 22:50:02 +00:00
: null,
2023-08-17 00:48:45 +00:00
search
2021-04-12 18:05:09 +00:00
}
}
2021-03-25 19:29:24 +00:00
})