fsdb/organizers/by_phone.ts

35 lines
1.1 KiB
TypeScript

import sanitize from '../utils/sanitize.ts';
const PHONE_REGEX =
/^(?<country_code>\+?\d{1,3})?[\s.x-]?\(?(?<area_code>\d{3})\)?[\s.x-]?(?<central_office_code>\d{3})[\s.x-]?(?<subscriber_code>\d{4})$/;
export default function by_phone(phone: string): string[] {
const { groups: { country_code, area_code, central_office_code, subscriber_code } } = {
groups: {
country_code: undefined,
area_code: undefined,
central_office_code: undefined,
subscriber_code: undefined
},
...(phone.match(PHONE_REGEX) ?? {})
};
if (
typeof area_code !== 'string' || typeof central_office_code !== 'string' ||
typeof subscriber_code !== 'string'
) {
return [];
}
const normalized_number = `${sanitize(area_code)}-${sanitize(central_office_code)}-${sanitize(subscriber_code)}`;
// for example, a symlinking index based on this organizer might look like:
// fsdb root index country_code office_code area_code phone
// /path/to/db/root/.indexes/phone/1/213/555/213-555-1234
return [
sanitize(country_code ?? '1'),
sanitize(area_code),
sanitize(central_office_code),
normalized_number,
`${normalized_number}.json`
];
}