traxxx-web/src/web/graphql.js

100 lines
2.1 KiB
JavaScript

import config from 'config';
import { format } from 'date-fns';
import {
graphql,
buildSchema,
GraphQLScalarType,
} from 'graphql';
import {
scenesSchema,
fetchScenesGraphql,
fetchScenesByIdGraphql,
} from './scenes.js';
import {
entitiesSchema,
fetchEntitiesGraphql,
fetchEntitiesByIdGraphql,
} from './entities.js';
import {
actorsSchema,
fetchActorsGraphql,
fetchActorsByIdGraphql,
} from './actors.js';
import { verifyKey } from '../auth.js';
const schema = buildSchema(`
type Query {
movies(
limit: Int = 30
): ReleasesResult
}
scalar Date
${scenesSchema}
${actorsSchema}
${entitiesSchema}
`);
const DateTimeScalar = new GraphQLScalarType({
name: 'DateTime',
serialize(value) {
if (value instanceof Date) {
return value.toISOString();
}
return value;
},
});
const DateScalar = new GraphQLScalarType({
name: 'Date',
serialize(value) {
if (value instanceof Date) {
return format(value, 'yyyy-MM-dd');
}
return value;
},
});
export async function graphqlApi(req, res) {
if (!config.apiAccess.graphqlEnabled) {
res.status(404).send();
return;
}
await verifyKey(req.headers['api-user'], req.headers['api-key'], req);
const data = await graphql({
schema,
source: req.body.query,
variableValues: req.body.variables,
resolvers: {
DateTimeScalar,
DateScalar,
},
rootValue: {
scenes: async (query) => fetchScenesGraphql(query, req),
scene: async (query) => fetchScenesByIdGraphql(query, req),
scenesById: async (query) => fetchScenesByIdGraphql(query, req),
actors: async (query) => fetchActorsGraphql(query, req),
actor: async (query, args, info) => fetchActorsByIdGraphql(query, req, info),
actorsById: async (query, args, info) => fetchActorsByIdGraphql(query, req, info),
entities: async (query) => fetchEntitiesGraphql(query, req),
entity: async (query, args, info) => fetchEntitiesByIdGraphql(query, req, info),
entitiesBySlug: async (query, args, info) => fetchEntitiesByIdGraphql(query, req, info),
entitiesById: async (query, args, info) => fetchEntitiesByIdGraphql(query, req, info),
},
});
// console.log(data);
res.send(data);
}