mirror of
https://github.com/tcgdex/cards-database.git
synced 2025-06-17 09:59:19 +00:00
@ -1,9 +1,15 @@
|
||||
import express from 'express'
|
||||
import { graphqlHTTP } from 'express-graphql'
|
||||
import fs from 'fs'
|
||||
import { buildSchema, formatError, GraphQLError } from 'graphql'
|
||||
import { buildSchema, GraphQLError } from 'graphql'
|
||||
import { createHandler } from 'graphql-http/lib/use/express'
|
||||
import { type ruruHTML as RuruHTML } from 'ruru/dist/server'
|
||||
/** @ts-expect-error typing is not correctly mapped (real type at ruru/dist/server.d.ts) */
|
||||
import { makeHTMLParts, ruruHTML as tmp } from 'ruru/server'
|
||||
import resolver from './resolver'
|
||||
|
||||
|
||||
const ruruHTML: typeof RuruHTML = tmp
|
||||
|
||||
// Init Express Router
|
||||
const router = express.Router()
|
||||
|
||||
@ -14,11 +20,19 @@ const router = express.Router()
|
||||
const schema = buildSchema(fs.readFileSync('./public/v2/graphql.gql', 'utf-8'))
|
||||
|
||||
// Error Logging for debugging
|
||||
function graphQLErrorHandle(error: GraphQLError) {
|
||||
function graphQLErrorHandle(error: Readonly<GraphQLError | Error>) {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
console.error(error)
|
||||
}
|
||||
if (error.source) {
|
||||
if (!('source' in error)) {
|
||||
const columns = (process?.stdout?.columns ?? 32) - 7
|
||||
const dashes = ''.padEnd(columns / 2, '-')
|
||||
|
||||
console.error(`\x1b[91m${dashes} ERROR ${dashes}\x1b[0m`)
|
||||
console.error('GraphQL Error')
|
||||
console.error(error.message)
|
||||
console.error(`\x1b[91m${dashes} ERROR ${dashes}\x1b[0m`)
|
||||
} else if (error.source) {
|
||||
const columns = (process?.stdout?.columns ?? 32) - 7
|
||||
const dashes = ''.padEnd(columns / 2, '-')
|
||||
|
||||
@ -28,18 +42,24 @@ function graphQLErrorHandle(error: GraphQLError) {
|
||||
console.error(error.source?.body)
|
||||
console.error(`\x1b[91m${dashes} ERROR ${dashes}\x1b[0m`)
|
||||
}
|
||||
return formatError(error)
|
||||
return error
|
||||
}
|
||||
|
||||
const graphql = graphqlHTTP({
|
||||
schema,
|
||||
const graphql = createHandler({
|
||||
schema: schema,
|
||||
rootValue: resolver,
|
||||
graphiql: true,
|
||||
customFormatErrorFn: graphQLErrorHandle
|
||||
formatError: graphQLErrorHandle
|
||||
})
|
||||
|
||||
// Add graphql to the route
|
||||
router.get('/', graphql)
|
||||
router.get('/', (_, res) => {
|
||||
res.type('html')
|
||||
|
||||
res.end(ruruHTML({ endpoint: '/v2/graphql' }, {
|
||||
...makeHTMLParts(),
|
||||
titleTag: '<title>GraphiQL - TCGdex API V2</title>'
|
||||
}))
|
||||
})
|
||||
router.post('/', graphql)
|
||||
|
||||
export default router
|
||||
|
Reference in New Issue
Block a user