n39librarian/middleware/utils/censorBookData.ts

26 lines
745 B
TypeScript

import { Book } from "../types/Book";
const censorExceptFirstLast = (data: string) => {
const regex = /(?<!^).(?!$)/g;
return data.replace(regex, "*");
};
const censorContactInfo = (data: string) => {
if (data.includes("@")) {
const regex = /(\w{1})[\w.]+([\w.])+@([\w.]+\w)/;
return data.replace(regex, "$1**$2@$3");
} else {
return censorExceptFirstLast(data);
}
};
export const censorBookData = (books: Book[], isAdmin: boolean): Book[] =>
isAdmin
? books
: books.map((book) => ({
...book,
checkoutBy: !book.checkoutBy
? book.checkoutBy
: censorExceptFirstLast(book.checkoutBy),
contact: !book.contact ? book.contact : censorContactInfo(book.contact),
}));