51 lines
1.5 KiB
TypeScript
51 lines
1.5 KiB
TypeScript
import { queryTTL } from '@/config/graphql/ttl';
|
|
import getUrls from '@/config/urls';
|
|
import { createRedisInstance } from '@/redis/client';
|
|
import { HttpError } from '@/utils/error';
|
|
import type { ApolloQueryResult, GraphQLRequest } from '@apollo/client';
|
|
import type { NextApiRequest, NextApiResponse } from 'next';
|
|
|
|
const { URL_CRM_GRAPHQL } = getUrls();
|
|
|
|
const redis = createRedisInstance();
|
|
|
|
function getHeaders(req: NextApiRequest) {
|
|
const headers = new Headers();
|
|
Object.keys(req.headers).forEach((key) => {
|
|
const value = req.headers[key];
|
|
if (value !== undefined && typeof value === 'string') headers.set(key, value);
|
|
});
|
|
|
|
return headers;
|
|
}
|
|
|
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|
const headers = getHeaders(req);
|
|
|
|
const { operationName, variables } = req.body as GraphQLRequest;
|
|
const key = `${operationName} ${JSON.stringify(variables)}`;
|
|
const cached = await redis.get(key);
|
|
|
|
if (cached) return res.send({ ...JSON.parse(cached), cached: true });
|
|
|
|
const response = await fetch(URL_CRM_GRAPHQL, {
|
|
body: JSON.stringify(req.body),
|
|
headers,
|
|
method: req.method,
|
|
});
|
|
|
|
const data = (await response.json()) as ApolloQueryResult<unknown>;
|
|
|
|
if (!response.ok || data?.error || data?.errors?.length) {
|
|
throw new HttpError(response.statusText, response.status || 500);
|
|
}
|
|
|
|
if (operationName) {
|
|
const ttl = queryTTL[operationName];
|
|
|
|
if (data && ttl !== false) await redis.set(key, JSON.stringify(data), 'EX', ttl);
|
|
}
|
|
|
|
return res.send(data);
|
|
}
|