import { NextApiRequest, NextApiResponse } from 'next' import { brief as briefTemplate } from '../../../lib/templates' import renderer from '../../../lib/renderer' import * as store from '../../../lib/store' import { IDocProps } from '../../../interfaces/IDocProps' const TEMPLATES: { [key: string]: (options: IDocProps) => string } = { brief: briefTemplate, } const handler = async (req: NextApiRequest, res: NextApiResponse) => { if (req.method !== 'POST') { res.status(405).json({ statusCode: 405, message: 'Method Not Allowed' }) return } try { const { query: { template: templateArg }, } = req const options = req.body const templateName = Array.isArray(templateArg) ? templateArg[0] : templateArg const template = TEMPLATES[templateName] if (!template) { res.status(404).json({ statusCode: 404, message: 'Template not specified availabe' }) return } const texDoc = template(options) const id = await renderer(texDoc) const storeData = Object.assign({}, options, { id, created: new Date().toISOString(), template: templateName, }) await store.add(storeData) res.status(200).json({ id: id }) } catch (err) { console.error('Error:', err, 'for', req.url) res.status(500).json({ error: err.toString() }) } } export default handler