From d2b30c14b737a51db29eb8fad4575c88af915dfb Mon Sep 17 00:00:00 2001 From: Riccardo Fano Date: Sun, 4 Feb 2024 15:51:58 +0100 Subject: [PATCH] Setup api endpoint --- core/invertGraph.ts | 12 ++++++++++++ pages/api/inverted/inheritance.ts | 21 +++++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 pages/api/inverted/inheritance.ts diff --git a/core/invertGraph.ts b/core/invertGraph.ts index 1dd9da7..164e26e 100644 --- a/core/invertGraph.ts +++ b/core/invertGraph.ts @@ -11,6 +11,18 @@ type InvertedPerson = { type InvertedPersonList = Record +export function defaultRoot(): Person { + return { + id: '0', + name: 'Defunto', + available: false, + degree: 0, + root: null, + category: 'children', + relatives: [], + } +} + export function invertGraph(root: Person, list: InvertedPersonList): PersonList { const personList: PersonList = { '0': root } for (const person of Object.values(list)) { diff --git a/pages/api/inverted/inheritance.ts b/pages/api/inverted/inheritance.ts new file mode 100644 index 0000000..fcb7798 --- /dev/null +++ b/pages/api/inverted/inheritance.ts @@ -0,0 +1,21 @@ +import { NextApiRequest, NextApiResponse } from 'next' +import { calculateInheritance } from '../../../core/inheritance' +import { defaultRoot, invertGraph } from '../../../core/invertGraph' + +export default function handler(req: NextApiRequest, res: NextApiResponse) { + if (req.method !== 'POST') { + return res.status(405).send({ error: 'Method not allowed' }) + } + + if (req.headers['content-type'] !== 'application/json') { + return res.status(400).send({ error: 'Content type not allowed' }) + } + + try { + const graph = invertGraph(defaultRoot(), req.body) + const result = calculateInheritance(graph) + return res.json(result) + } catch (error) { + return res.status(500).send({ error: 'Failed to parse body' }) + } +}