|
1 | 1 | import { sha256 } from '@douglasneuroinformatics/libcrypto'; |
2 | | -import { $ClinicalSubjectIdentificationData } from '@opendatacapture/schemas/subject'; |
3 | 2 | import type { ClinicalSubjectIdentificationData, Subject } from '@opendatacapture/schemas/subject'; |
4 | 3 | import { transliterate } from 'transliteration'; |
5 | 4 | import type { SetNonNullable } from 'type-fest'; |
6 | 5 |
|
7 | 6 | type SubjectPersonalInfo = Pick<Subject, 'dateOfBirth' | 'firstName' | 'id' | 'lastName' | 'sex'>; |
8 | 7 |
|
| 8 | +function parseClinicalSubjectIdentificationData({ |
| 9 | + dateOfBirth, |
| 10 | + firstName, |
| 11 | + lastName, |
| 12 | + sex |
| 13 | +}: { |
| 14 | + [key: string]: unknown; |
| 15 | +}): ClinicalSubjectIdentificationData { |
| 16 | + if (!(dateOfBirth instanceof Date)) { |
| 17 | + throw new Error('Invalid or missing dateOfBirth: Expected a Date object.'); |
| 18 | + } else if (typeof firstName !== 'string') { |
| 19 | + throw new Error('Invalid or missing firstName: Expected a string.'); |
| 20 | + } else if (typeof lastName !== 'string') { |
| 21 | + throw new Error('Invalid or missing lastName: Expected a string.'); |
| 22 | + } else if (!(sex === 'MALE' || sex === 'FEMALE')) { |
| 23 | + throw new Error('Invalid or missing sex: Expected "MALE" or "FEMALE".'); |
| 24 | + } |
| 25 | + return { |
| 26 | + dateOfBirth, |
| 27 | + firstName, |
| 28 | + lastName, |
| 29 | + sex |
| 30 | + }; |
| 31 | +} |
| 32 | + |
9 | 33 | export async function generateSubjectHash(data: ClinicalSubjectIdentificationData): Promise<string> { |
10 | 34 | // In case the type system breaks somewhere, this should crash at runtime instead of generating an incorrect ID which would cause chaos |
11 | | - const { dateOfBirth, firstName, lastName, sex } = await $ClinicalSubjectIdentificationData.parseAsync(data); |
| 35 | + const { dateOfBirth, firstName, lastName, sex } = parseClinicalSubjectIdentificationData(data); |
12 | 36 | const shortDateOfBirth = dateOfBirth.toISOString().split('T')[0]; |
13 | 37 | const info = firstName + lastName + shortDateOfBirth + sex; |
14 | 38 | const source = transliterate(info.toUpperCase().replaceAll('-', '')); |
|
0 commit comments