finished contact migration to typescript

This commit is contained in:
canove
2020-09-19 21:41:28 -03:00
parent 5b54c4df41
commit 70c391e8ef
4 changed files with 235 additions and 230 deletions

View File

@@ -1,10 +1,17 @@
import AppError from "../../errors/AppError";
import Contact from "../../models/Contact";
import ContactCustomField from "../../models/ContactCustomField";
interface ExtraInfo {
id?: number;
name: string;
value: string;
}
interface ContactData {
email?: string;
number?: string;
name?: string;
extraInfo?: ExtraInfo[];
}
interface Request {
@@ -16,21 +23,41 @@ const UpdateContactService = async ({
contactData,
contactId
}: Request): Promise<Contact> => {
const { email, name, number } = contactData;
const { email, name, number, extraInfo } = contactData;
const contact = await Contact.findOne({
where: { id: contactId },
attributes: ["id", "name", "number", "email"]
attributes: ["id", "name", "number", "email"],
include: ["extraInfo"]
});
if (!contact) {
throw new AppError("No contact found with this ID.", 404);
}
if (extraInfo) {
await Promise.all(
extraInfo.map(async info => {
await ContactCustomField.upsert({ ...info, contactId: contact.id });
})
);
await Promise.all(
contact.extraInfo.map(async oldInfo => {
const stillExists = extraInfo.findIndex(info => info.id === oldInfo.id);
if (stillExists === -1) {
await ContactCustomField.destroy({ where: { id: oldInfo.id } });
}
})
);
}
await contact.update({
name,
number,
email
email,
extraInfo
});
return contact;