1
0
Fork 0
mirror of https://github.com/betagouv/mon-entreprise synced 2025-02-09 04:05:01 +00:00
mon-entreprise/server/source/utils.ts
Benjamin Arias a51920b44c
Support Usager : Implémentation de la messagerie Crisp (#2329)
* feat: Ajoute l'iframe crisp ainsi que le bloc custom html

* wip

* feat: Renomme le dossier standup.. + ajoute la fonction crisp

* fix: Install not broken version + add update meta

* feat: Ajoute le formulaire

* fix: Corrige htmlFor et id

* feat: Ajoute la logique pour récupérer nombre de réponses et les issues

* fix: uncomment stuff

* fix: Retire log

* chore: Renomme fonction

* chore: Renomme fonction

* chore: Renomme fonction

* feat: Retire commentaires

* fix: Refacto urlParams

* chore : Nettoyage de reliquats

* fix : Ajoute TextAreaField et utilise TextField

* fix: Style issues

* fix: Améliore types

* feat: Cleaning

* feat: Ajoute variable d'env website id

* feat: Met à jour README

* wip placeholder url

* feat: Ajoute une fonction de validation du body

* feat: Ajoute validation

* chore: update yarn.lock

* fix: Add missing secret ref + cleaning
2022-10-24 15:03:14 +02:00

57 lines
1.5 KiB
TypeScript

import { BodyType } from './functions/send-crisp-message.js'
type CamelCase<S extends string> =
S extends `${infer P1}_${infer P2}${infer P3}`
? `${Lowercase<P1>}${Uppercase<P2>}${CamelCase<P3>}`
: Lowercase<S>
const snakeToCamelCase = <T extends string>(str: T) =>
str
.replace(/_/g, ' ')
.replace(/(?<!\p{L})\p{L}|\s+/gu, (m) => (+m === 0 ? '' : m.toUpperCase()))
.replace(/^./, (m) => m?.toLowerCase()) as CamelCase<T>
export type KeysToCamelCase<T> = {
[K in keyof T as CamelCase<string & K>]: T[K]
}
export const snakeToCamelCaseKeys = <T extends object>(object: T) =>
Object.fromEntries(
Object.entries(object).map(
([key, value]) => [snakeToCamelCase(key), value],
{}
)
) as KeysToCamelCase<T>
export const shuffleArray = <T>(array: T[]) => {
const shuffle = [...array]
for (let i = shuffle.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
const [shuffleI, shuffleJ] = [shuffle[i], shuffle[j]]
shuffle[i] = shuffleJ
shuffle[j] = shuffleI
}
return shuffle
}
const isStringAndNotEmpty = (value: string) =>
value !== undefined && value !== '' && typeof value === 'string'
const SHORT_MAX_LENGTH = 254
export const validateCrispBody = (body: BodyType): BodyType => {
const { subject, message, email } = body || {}
if (
isStringAndNotEmpty(subject) &&
subject.length <= SHORT_MAX_LENGTH &&
isStringAndNotEmpty(message) &&
isStringAndNotEmpty(email) &&
email.length <= SHORT_MAX_LENGTH
) {
return body
}
throw Error('Body validation failed.')
}