Skip to content

Commit

Permalink
feat(overige-objecten-api): add post/patch to kennisartikel
Browse files Browse the repository at this point in the history
  • Loading branch information
AliKdhim87 authored and Robbert committed Dec 10, 2024
1 parent a7ab4b6 commit 608f2cd
Show file tree
Hide file tree
Showing 6 changed files with 593 additions and 132 deletions.
215 changes: 156 additions & 59 deletions apps/overige-objecten-api/src/controllers/objects/create.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
import type { RequestHandler } from 'express';
import snakeCase from 'lodash.snakecase';
import slugify from 'slugify';
import { v4 } from 'uuid';
import { CREATE_VAC } from '../../queries';
import type { DataVacItem } from '../../strapi-product-type';
import { CREATE_INTERNAL_FIELD, CREATE_KENNISARTIKEL, CREATE_VAC } from '../../queries';
import type { CreateInternalField, CreateProduct, DataVacItem } from '../../strapi-product-type';
import type { components } from '../../types/openapi';
import { fetchData, getCurrentTypeParam, getTheServerURL } from '../../utils';

import {
fetchData,
generateKennisartikelObject,
getCurrentTypeParam,
getTheServerURL,
mapContentByCategory,
} from '../../utils';
type VACData = {
data: {
createVac: {
Expand All @@ -14,69 +20,160 @@ type VACData = {
};
};

export const createVacController: RequestHandler = async (req, res, next) => {
const isAuthHasToken = req.headers?.authorization?.startsWith('Token');
const tokenAuth = isAuthHasToken ? req.headers?.authorization?.split(' ')[1] : req.headers?.authorization;
const locale = req.query?.locale || 'nl';
const graphqlURL = new URL('/graphql', process.env.STRAPI_PRIVATE_URL);
const serverURL = getTheServerURL(req);
const categoryToKeyMap: { [key: string]: string } = {
bewijs: 'bewijs',
bezwaarEnBeroep: 'bezwaar',
contact: 'contact',
kostenEnBetaalmethoden: 'kosten',
notice: 'bijzonderheden',
procedureBeschrijving: 'aanvraag',
tekst: 'inleiding',
uitersteTermijn: 'termijn',
vereisten: 'voorwaarden',
wtdBijGeenReactie: 'wat te doen bij geen reactie',
};

export const createVacController: RequestHandler = async (req, res, next) => {
let response;
try {
const isAuthHasToken = req.headers?.authorization?.startsWith('Token');
const tokenAuth = isAuthHasToken ? req.headers?.authorization?.split(' ')[1] : req.headers?.authorization;
const locale = req.query?.locale || 'nl';
const graphqlURL = new URL('/graphql', process.env.STRAPI_PRIVATE_URL);
const serverURL = getTheServerURL(req);
const body = req.body as components['schemas']['ObjectData'];
const vac = body?.record?.data as components['schemas']['vac'];
const vacSchemaURL = new URL('api/v2/objecttypes/vac', serverURL).href;
const { isVac } = getCurrentTypeParam(body.type);
const { isVac, isKennisartikel } = getCurrentTypeParam(body.type);

if (!isVac) {
return res.status(400).json({ message: 'Type is not allowed' });
}
if (isVac) {
const vac = body?.record?.data as components['schemas']['vac'];
const vacSchemaURL = new URL('api/v2/objecttypes/vac', serverURL).href;
const vacPayload = {
publishedAt: new Date(),
vac: {
vraag: vac?.vraag,
antwoord: vac?.antwoord,
doelgroep: snakeCase(vac?.doelgroep),
uuid: v4(),
status: vac?.status,
afdelingen: vac?.afdelingen?.map(({ afdelingNaam }) => ({
afdelingId: v4(),
afdelingNaam,
})),
toelichting: vac?.toelichting,
trefwoorden: vac?.trefwoorden,
},
};
const { data: responseData } = await fetchData<VACData>({
url: graphqlURL.href,
query: CREATE_VAC,
variables: { locale, data: vacPayload },
headers: {
Authorization: `Bearer ${tokenAuth}`,
},
});
const uuid = responseData?.createVac?.data?.attributes?.vac?.uuid;
const createdAt = responseData?.createVac?.data?.attributes?.createdAt;
const vacUrl = new URL(`/api/v2/objects/${uuid}`, serverURL).href;
response = {
uuid,
type: vacSchemaURL,
url: vacUrl,
record: {
index: parseInt(responseData?.createVac?.data?.id, 10),
startAt: createdAt,
typeVersion: 3,
data: {
...responseData?.createVac?.data?.attributes?.vac,
url: vacUrl,
},
geometry: null,
endAt: null,
registrationAt: createdAt,
},
};
} else if (isKennisartikel) {
const kennisartikel = body?.record?.data as components['schemas']['kennisartikel'];
const kennisartikelNl = kennisartikel?.vertalingen?.find(({ taal }) => taal === 'nl');

const vacPayload = {
publishedAt: new Date(),
vac: {
vraag: vac?.vraag,
antwoord: vac?.antwoord,
doelgroep: snakeCase(vac?.doelgroep),
const kennisartikelenBlocks = Object.entries(kennisartikelNl || {})
.map(([key, value]) => {
const mappedContent = mapContentByCategory(key, value as any, categoryToKeyMap);
if (Object.keys(mappedContent).length === 0) return null;
const [kennisartikelCategorie, content] = Object.entries(mappedContent)[0];
return { content, kennisartikelCategorie, __typename: 'ComponentComponentsUtrechtRichText' };
})
.filter(Boolean);
const deskMemo = kennisartikelNl?.deskMemo;
const kennisartikelPayload = {
title: kennisartikelNl?.titel,
slug: slugify(kennisartikelNl?.titel as string, { lower: true }),
uuid: v4(),
status: vac?.status,
afdelingen: vac?.afdelingen?.map(({ afdelingNaam }) => ({
afdelingId: v4(),
afdelingNaam,
})),
toelichting: vac?.toelichting,
trefwoorden: vac?.trefwoorden,
},
};

const { data: responseData } = await fetchData<VACData>({
url: graphqlURL.href,
query: CREATE_VAC,
variables: { locale, data: vacPayload },
headers: {
Authorization: `Bearer ${tokenAuth}`,
},
});
const uuid = responseData?.createVac?.data?.attributes?.vac?.uuid;
const createdAt = responseData?.createVac?.data?.attributes?.createdAt;
const vacUrl = new URL(`/api/v2/objects/${uuid}`, serverURL).href;
metaTags: {
keymatch: kennisartikelNl?.trefwoorden?.map((trefwoord) => trefwoord.trefwoord).join(','),
title: kennisartikelNl?.titel,
description: ' ', // This field is required and essential for the product page but is not used in the Overige-Objecten API.
},
sections: kennisartikelenBlocks,
kennisartikelMetadata: {
uuid: v4(),
afdelingen: kennisartikel.afdelingen?.map(({ afdelingNaam }) => ({
afdelingId: v4(),
afdelingNaam,
})),
doelgroep: snakeCase(kennisartikel.doelgroep),
productAanwezig: kennisartikel.productAanwezig,
productValtOnder: kennisartikel.productValtOnder,
verantwoordelijkeOrganisatie: kennisartikel.verantwoordelijkeOrganisatie,
upnUri: kennisartikel.upnUri,
},
};
const internalFieldPayload = {
title: kennisartikelNl?.titel,
content: {
uuid: v4(),
contentBlock: {
content: deskMemo,
},
},
};
if (deskMemo) {
const { data: internalResponse } = await fetchData<CreateInternalField>({
url: graphqlURL.href,
query: CREATE_INTERNAL_FIELD,
variables: { locale, data: internalFieldPayload },
headers: {
Authorization: `Bearer ${tokenAuth}`,
},
});
// check if the internal field was created
if (internalResponse?.createInternalField?.data?.attributes?.content?.id) {
kennisartikelPayload.sections.push({
__typename: 'ComponentComponentsInternalBlockContent',
internal_field: internalResponse?.createInternalField?.data?.id,
__component: 'components.internal-block-content',
} as any);
}
}

return res.status(201).json({
uuid,
type: vacSchemaURL,
url: vacUrl,
record: {
index: parseInt(responseData?.createVac?.data?.id, 10),
startAt: createdAt,
typeVersion: 3,
data: {
...responseData?.createVac?.data?.attributes?.vac,
url: vacUrl,
const { data: responseData } = await fetchData<{ data: CreateProduct }>({
url: graphqlURL.href,
query: CREATE_KENNISARTIKEL,
variables: { locale, data: kennisartikelPayload },
headers: {
Authorization: `Bearer ${tokenAuth}`,
},
geometry: null,
endAt: null,
registrationAt: createdAt,
},
});
});

const results = generateKennisartikelObject({
attributes: responseData?.createProduct?.data?.attributes,
url: serverURL,
id: responseData?.createProduct?.data?.id,
});
response = results;
} else {
return res.status(400).json({ message: 'Type is not allowed' });
}
return res.status(201).json(response);
} catch (error) {
// Forward any errors to the error handler middleware
next(error);
Expand Down
Loading

0 comments on commit 608f2cd

Please sign in to comment.