45 lines
1.8 KiB
TypeScript
45 lines
1.8 KiB
TypeScript
import { NextApiRequest, NextApiResponse } from 'next';
|
|
import { PrismaClient } from '@prisma/client';
|
|
|
|
const common = require('../../../../src/helpers/common');
|
|
const logger = require('../../../../src/logger');
|
|
|
|
// Utility to parse query parameters into a Prisma query
|
|
const parseQueryParams = (query: any) => {
|
|
return {
|
|
select: query.select ? JSON.parse(query.select) : undefined,
|
|
include: query.include ? JSON.parse(query.include) : undefined,
|
|
where: query.where ? JSON.parse(query.where) : undefined,
|
|
orderBy: query.orderBy ? JSON.parse(query.orderBy) : undefined,
|
|
skip: query.skip ? parseInt(query.skip, 10) : undefined,
|
|
limit: query.limit ? parseInt(query.limit, 10) : undefined,
|
|
distinct: query.distinct ? query.distinct.split(',') : undefined,
|
|
};
|
|
};
|
|
|
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|
const prisma: PrismaClient = common.getPrismaClient();
|
|
const modelArray = (req.query.model || (req.body && req.body.model)) as string[];
|
|
let queryOptions = {};
|
|
|
|
if (req.method === 'POST' && req.headers['content-type']?.includes('application/json')) {
|
|
// Handle POST request
|
|
queryOptions = req.body;
|
|
} else {
|
|
// Handle GET request
|
|
queryOptions = parseQueryParams(req.query);
|
|
}
|
|
|
|
try {
|
|
if (!modelArray || modelArray.length === 0) {
|
|
throw new Error('Model is required as a part of the URL path.');
|
|
}
|
|
const modelName = modelArray[0]; // Get the first part of the model array
|
|
const result = await prisma[modelName].findMany(queryOptions);
|
|
res.status(200).json(result);
|
|
} catch (error) {
|
|
console.error(error);
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
}
|