-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpdfService.ts
148 lines (138 loc) · 4.47 KB
/
pdfService.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import {
I18nTranslationMap,
I18nTranslationReplacements,
NavFormType,
Submission,
translationUtils,
yourInformationUtils,
} from '@navikt/skjemadigitalisering-shared-domain';
import correlator from 'express-correlation-id';
import { config } from '../../../config/config';
import { logger } from '../../../logger';
import { appMetrics } from '../../../services';
import { base64Decode, base64Encode } from '../../../utils/base64';
import { responseToError, synchronousResponseToError } from '../../../utils/errorHandling';
import fetchWithRetry, { HeadersInit } from '../../../utils/fetchWithRetry';
import { createHtmlFromSubmission } from './htmlBuilder';
const { skjemabyggingProxyUrl, gitVersion } = config;
export const createPdfAsByteArray = async (
accessToken: string,
form: NavFormType,
submission: Submission,
submissionMethod: string,
translations: I18nTranslationMap,
language: string,
) => {
const pdf = await createPdf(accessToken, form, submission, submissionMethod, translations, language);
return Array.from(base64Decode(pdf.data) ?? []);
};
export const createPdf = async (
accessToken: string,
form: NavFormType,
submission: Submission,
submissionMethod: string,
translations: I18nTranslationMap,
language: string,
) => {
const translate = (text: string, textReplacements?: I18nTranslationReplacements) =>
translationUtils.translateWithTextReplacements({
translations,
originalText: text,
params: textReplacements,
currentLanguage: language,
});
const html = createHtmlFromSubmission(form, submission, submissionMethod, translate, language);
if (!html || Object.keys(html).length === 0) {
throw Error('Missing HTML for generating PDF.');
}
const yourInformation = yourInformationUtils.getYourInformation(form, submission.data);
let identityNumber: string;
if (yourInformation?.identitet?.identitetsnummer) {
identityNumber = yourInformation.identitet.identitetsnummer;
} else if (submission.data.fodselsnummerDNummerSoker) {
// This is the old format of the object, which is still used in some forms.
identityNumber = submission.data.fodselsnummerDNummerSoker as string;
} else {
identityNumber = '—';
}
appMetrics.exstreamPdfRequestsCounter.inc();
let errorOccurred = false;
const stopMetricRequestDuration = appMetrics.outgoingRequestDuration.startTimer({
service: 'exstream',
method: 'createPdf',
});
try {
return await createPdfFromHtml(
accessToken,
translate(form.title),
form.properties.skjemanummer,
language,
html,
identityNumber,
);
} catch (e) {
errorOccurred = true;
appMetrics.exstreamPdfFailuresCounter.inc();
throw e;
} finally {
const durationSeconds = stopMetricRequestDuration({ error: String(errorOccurred) });
logger.info(`Request to exstream pdf service completed after ${durationSeconds} seconds`, {
error: errorOccurred,
durationSeconds,
});
}
};
export const createPdfFromHtml = async (
azureAccessToken: string,
title: string,
skjemanummer: string,
language: string,
html: string,
pid: string,
) => {
const response = await fetchWithRetry(`${skjemabyggingProxyUrl}/exstream`, {
retry: 3,
headers: {
Authorization: `Bearer ${azureAccessToken}`,
'x-correlation-id': correlator.getId(),
'Content-Type': 'application/json',
} as HeadersInit,
method: 'POST',
body: JSON.stringify({
content: {
contentType: 'application/json',
data: base64Encode(
JSON.stringify({
dokumentTittel: title,
spraakkode: language,
blankettnr: skjemanummer,
brukersFnr: pid,
skjemaversjon: gitVersion,
html: base64Encode(html),
}),
),
async: 'true',
},
RETURNFORMAT: 'PDF',
RETURNDATA: 'TRUE',
}),
});
if (response.ok) {
const json: any = await response.json();
if (!json.data?.result?.[0]?.content) {
if (json.data?.id) {
throw synchronousResponseToError(
`Feil i responsdata fra Exstream på id "${json.data?.id}"`,
json,
response.status,
response.url,
true,
);
} else {
throw synchronousResponseToError('Feil i responsdata fra Exstream', json, response.status, response.url, true);
}
}
return json.data.result[0].content;
}
throw await responseToError(response, 'Feil ved generering av PDF hos Exstream', true);
};