stacker.news/api/ssrApollo.js

84 lines
1.9 KiB
JavaScript
Raw Normal View History

2021-04-14 23:56:29 +00:00
import { ApolloClient, InMemoryCache } from '@apollo/client'
import { SchemaLink } from '@apollo/client/link/schema'
import { mergeSchemas } from 'graphql-tools'
import { getSession } from 'next-auth/client'
import resolvers from './resolvers'
import typeDefs from './typeDefs'
import models from './models'
2021-10-26 20:49:37 +00:00
import { print } from 'graphql'
2021-10-28 19:59:53 +00:00
import lnd from './lnd'
2022-01-26 15:35:14 +00:00
import search from './search'
import { ME_SSR } from '../fragments/users'
2021-11-28 17:29:17 +00:00
import { getPrice } from '../components/price'
2021-04-14 23:56:29 +00:00
2021-10-28 19:59:53 +00:00
export default async function getSSRApolloClient (req, me = null) {
2021-07-08 00:15:27 +00:00
const session = req && await getSession({ req })
return new ApolloClient({
ssrMode: true,
link: new SchemaLink({
schema: mergeSchemas({
schemas: typeDefs,
resolvers: resolvers
}),
context: {
2021-04-14 23:56:29 +00:00
models,
2022-04-21 22:50:02 +00:00
me: session
? session.user
2022-04-21 22:50:02 +00:00
: me,
2022-01-26 15:35:14 +00:00
lnd,
search
2021-04-14 23:56:29 +00:00
}
}),
cache: new InMemoryCache()
})
}
2021-10-26 20:49:37 +00:00
export function getGetServerSideProps (query, variables = null, notFoundFunc, requireVar) {
2021-12-16 17:27:12 +00:00
return async function ({ req, query: params }) {
2021-10-26 20:49:37 +00:00
const client = await getSSRApolloClient(req)
2022-01-27 20:15:18 +00:00
const vars = { ...params, ...variables }
if (requireVar && !vars[requireVar]) {
return {
notFound: true
}
}
2022-04-21 22:50:02 +00:00
let error = null; let data = null; let props = {}
if (query) {
({ error, data } = await client.query({
query,
variables: vars
}))
2021-10-26 20:49:37 +00:00
2022-04-21 22:50:02 +00:00
if (error || !data || (notFoundFunc && notFoundFunc(data))) {
return {
notFound: true
}
}
props = {
apollo: {
query: print(query),
variables: { ...params, ...variables }
}
2021-10-26 20:49:37 +00:00
}
}
2021-11-28 17:29:17 +00:00
const { data: { me } } = await client.query({
query: ME_SSR
2021-11-28 17:29:17 +00:00
})
const price = await getPrice()
2021-10-26 20:49:37 +00:00
return {
props: {
2022-04-21 22:50:02 +00:00
...props,
2021-11-28 17:29:17 +00:00
me,
price,
2021-10-26 20:49:37 +00:00
data
}
}
}
}