From 866b602244be7dfcbe4eb12e2888a5d421a5f6ce Mon Sep 17 00:00:00 2001 From: Julien Oculi Date: Mon, 15 Jan 2024 21:29:47 +0100 Subject: [PATCH] refactor: extract and improve string processes to utils --- src/append_to_group.ts | 7 ++++--- src/create_users.ts | 14 ++++---------- utils.ts | 15 +++++++++++++++ 3 files changed, 23 insertions(+), 13 deletions(-) create mode 100644 utils.ts diff --git a/src/append_to_group.ts b/src/append_to_group.ts index 5f512ff..e7e2b64 100644 --- a/src/append_to_group.ts +++ b/src/append_to_group.ts @@ -1,11 +1,12 @@ -import { Redmine } from 'bluemine' -import { CsvEntry } from '../type.ts' +import { Redmine } from 'bluemine'; +import { CsvEntry } from '../type.ts'; +import { toLogin } from '../utils.ts'; async function addUsersToGroup(redmine: Redmine, csv: CsvEntry[]) { const users: { id: number; login: string }[] = [] for (const { firstname, lastname } of csv) { - const login = `${firstname.toLowerCase()}.${lastname.toLowerCase()}` + const login = toLogin(firstname, lastname) try { const list = await redmine.users.list({ limit: 1, name: login }) diff --git a/src/create_users.ts b/src/create_users.ts index 5c8a4f3..c6b7cf6 100644 --- a/src/create_users.ts +++ b/src/create_users.ts @@ -1,23 +1,17 @@ import { Redmine } from 'bluemine' import { CsvEntry } from '../type.ts' +import { capitalize, sanitize, toLogin } from '../utils.ts' async function createUsers(redmine: Redmine, csv: CsvEntry[]) { const userIds: number[] = [] - function capitalize(str: string): string { - const [first, ...tail] = str.split('') - return `${first.toLocaleUpperCase()}${ - tail.join('').toLocaleLowerCase() - }` - } - for (const { firstname, lastname, mail } of csv) { - const login = `${firstname.toLowerCase()}.${lastname.toLowerCase()}` + const login = toLogin(firstname, lastname) try { const { user } = await redmine.users.create({ - firstname: capitalize(firstname), - lastname: capitalize(lastname), + firstname: capitalize(sanitize(firstname)), + lastname: capitalize(sanitize(lastname)), mail: mail, login, sendCreationMail: true, diff --git a/utils.ts b/utils.ts new file mode 100644 index 0000000..50c8293 --- /dev/null +++ b/utils.ts @@ -0,0 +1,15 @@ +export function sanitize(str: string): string { + return str.replaceAll(' ', '_') +} + +export function capitalize(str: string): string { + return str + .split(' ') + .map(word => word.split('')) + .map(([firstLetter, ...tail]) => `${firstLetter.toLocaleUpperCase()}${tail.join().toLocaleLowerCase()}`) + .join(' ') +} + +export function toLogin(firstname: string, lastname: string): string { + return `${sanitize(firstname.toLocaleLowerCase())}.${sanitize(lastname.toLocaleLowerCase())}` +}