refactor: extract and improve string processes to utils

This commit is contained in:
Julien Oculi 2024-01-15 21:29:47 +01:00
parent a8a3edf22d
commit 866b602244
3 changed files with 23 additions and 13 deletions

View file

@ -1,11 +1,12 @@
import { Redmine } from 'bluemine' import { Redmine } from 'bluemine';
import { CsvEntry } from '../type.ts' import { CsvEntry } from '../type.ts';
import { toLogin } from '../utils.ts';
async function addUsersToGroup(redmine: Redmine, csv: CsvEntry[]) { async function addUsersToGroup(redmine: Redmine, csv: CsvEntry[]) {
const users: { id: number; login: string }[] = [] const users: { id: number; login: string }[] = []
for (const { firstname, lastname } of csv) { for (const { firstname, lastname } of csv) {
const login = `${firstname.toLowerCase()}.${lastname.toLowerCase()}` const login = toLogin(firstname, lastname)
try { try {
const list = await redmine.users.list({ limit: 1, name: login }) const list = await redmine.users.list({ limit: 1, name: login })

View file

@ -1,23 +1,17 @@
import { Redmine } from 'bluemine' import { Redmine } from 'bluemine'
import { CsvEntry } from '../type.ts' import { CsvEntry } from '../type.ts'
import { capitalize, sanitize, toLogin } from '../utils.ts'
async function createUsers(redmine: Redmine, csv: CsvEntry[]) { async function createUsers(redmine: Redmine, csv: CsvEntry[]) {
const userIds: number[] = [] 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) { for (const { firstname, lastname, mail } of csv) {
const login = `${firstname.toLowerCase()}.${lastname.toLowerCase()}` const login = toLogin(firstname, lastname)
try { try {
const { user } = await redmine.users.create({ const { user } = await redmine.users.create({
firstname: capitalize(firstname), firstname: capitalize(sanitize(firstname)),
lastname: capitalize(lastname), lastname: capitalize(sanitize(lastname)),
mail: mail, mail: mail,
login, login,
sendCreationMail: true, sendCreationMail: true,

15
utils.ts Normal file
View file

@ -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())}`
}