Skip to content

Commit

Permalink
add db logging for troubleshooting
Browse files Browse the repository at this point in the history
  • Loading branch information
bbohec committed Jul 7, 2023
1 parent ec7c3fa commit 0bcdaa6
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 55 deletions.
23 changes: 14 additions & 9 deletions back/src/adapters/secondary/pg/PgAgencyRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,16 +146,21 @@ export class PgAgencyRepository implements AgencyRepository {
}

public async getByIds(ids: AgencyId[]): Promise<AgencyDto[]> {
const query = format(
`SELECT id, name, status, kind, counsellor_emails, validator_emails,
admin_emails, questionnaire_url, email_signature, logo_url, ST_AsGeoJSON(position) AS position,
street_number_and_address, post_code, city, department_code, agency_siret, code_safir
FROM agencies
WHERE id IN (%L)`,
ids,
);
const query = `SELECT id, name, status, kind, counsellor_emails, validator_emails,
admin_emails, questionnaire_url, email_signature, logo_url, ST_AsGeoJSON(position) AS position,
street_number_and_address, post_code, city, department_code, agency_siret, code_safir
FROM agencies
WHERE id IN (%L)`;

const pgResult = await this.client.query(query);
const pgResult = await this.client
.query(format(query, ids))
.catch((error) => {
logger.error(
{ query, values: ids, error },
"PgAgencyRepository_getByIds_QueryErrored",
);
throw error;
});

if (pgResult.rows.length === 0) return [];
return pgResult.rows.map(persistenceAgencyToAgencyDto);
Expand Down
100 changes: 62 additions & 38 deletions back/src/adapters/secondary/pg/PgNotificationRepository.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
import { PoolClient } from "pg";
import format from "pg-format";
import { uniq } from "ramda";
import { exhaustiveCheck, NotificationsByKind } from "shared";
import {
EmailNotification,
exhaustiveCheck,
Notification,
NotificationId,
NotificationKind,
NotificationsByKind,
SmsNotification,
TemplatedEmail,
} from "shared";
import {
EmailNotificationFilters,
NotificationRepository,
} from "../../../domain/generic/notifications/ports/NotificationRepository";
import { createLogger } from "../../../utils/logger";

const logger = createLogger(__filename);
export class PgNotificationRepository implements NotificationRepository {
constructor(
private client: PoolClient,
Expand Down Expand Up @@ -90,19 +94,15 @@ export class PgNotificationRepository implements NotificationRepository {
return this.saveSmsNotification(notification);
case "email": {
const recipients = uniq(notification.templatedContent.recipients);
const cc = uniq(notification.templatedContent.cc ?? []).filter(
(ccEmail) => !recipients.includes(ccEmail),
);

const templatedContent = {
...notification.templatedContent,
recipients,
cc,
};

return this.saveEmailNotification({
...notification,
templatedContent,
templatedContent: {
...notification.templatedContent,
recipients,
cc: uniq(notification.templatedContent.cc ?? []).filter(
(ccEmail) => !recipients.includes(ccEmail),
),
},
});
}
default:
Expand Down Expand Up @@ -134,34 +134,46 @@ export class PgNotificationRepository implements NotificationRepository {
}

private async saveEmailNotification(notification: EmailNotification) {
const {
id,
createdAt,
followedIds,
templatedContent: { kind, recipients, cc, replyTo, params },
} = notification;

await this.client.query(
`
INSERT INTO notifications_email (id, email_kind, created_at, convention_id, establishment_siret, agency_id, params, reply_to_name, reply_to_email)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
`,
// prettier-ignore
[ id, kind, createdAt, followedIds.conventionId, followedIds.establishmentSiret, followedIds.agencyId, params, replyTo?.name, replyTo?.email],
);

const addRecipientsToQuery = format(
`INSERT INTO notifications_email_recipients (notifications_email_id, email, recipient_type) VALUES %L`,
recipients.map((recipient) => [id, recipient, "to"]),
);
await this.client.query(addRecipientsToQuery);
await this.insertNotificationEmail(notification);
await this.insertEmailRecipients("to", notification);
await this.insertEmailRecipients("cc", notification);
}

if (cc && cc.length > 0) {
const addRecipientsCcQuery = format(
`INSERT INTO notifications_email_recipients (notifications_email_id, email, recipient_type) VALUES %L`,
cc.map((recipient) => [id, recipient, "cc"]),
private async insertNotificationEmail({
id,
createdAt,
followedIds,
templatedContent,
}: EmailNotification) {
const query = `
INSERT INTO notifications_email (id, email_kind, created_at, convention_id, establishment_siret, agency_id, params, reply_to_name, reply_to_email)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
`;
// prettier-ignore
const values = [id, templatedContent.kind, createdAt, followedIds.conventionId, followedIds.establishmentSiret, followedIds.agencyId, templatedContent.params, templatedContent.replyTo?.name, templatedContent.replyTo?.email];
await this.client.query(query, values).catch((error) => {
logger.error(
{ query, values, error },
"PgNotificationRepository_insertNotificationEmail_QueryErrored",
);
await this.client.query(addRecipientsCcQuery);
throw error;
});
}

private async insertEmailRecipients(
recipientKind: "to" | "cc",
{ id, templatedContent }: EmailNotification,
) {
const values = recipientsByKind(id, recipientKind, templatedContent);
if (values.length > 0) {
const query = `INSERT INTO notifications_email_recipients (notifications_email_id, email, recipient_type) VALUES %L`;
await this.client.query(format(query, values)).catch((error) => {
logger.error(
{ query, values, error },
`PgNotificationRepository_insertEmailRecipients_${recipientKind}_QueryErrored`,
);
throw error;
});
}
}

Expand Down Expand Up @@ -251,3 +263,15 @@ const buildEmailNotificationObject = `JSON_STRIP_NULLS(JSON_BUILD_OBJECT(
'params', params
)
))`;

const recipientsByKind = (
id: NotificationId,
recipientKind: "to" | "cc",
{ recipients, cc }: TemplatedEmail,
): [id: NotificationId, recipient: string, recipientkind: "to" | "cc"][] => {
if (recipientKind === "to")
return recipients.map((recipient) => [id, recipient, recipientKind]);
if (recipientKind === "cc" && cc)
return cc.map((ccRecipient) => [id, ccRecipient, recipientKind]);
return [];
};
16 changes: 8 additions & 8 deletions back/src/adapters/secondary/pg/PgOutboxRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,14 @@ export class PgOutboxRepository implements OutboxRepository {
const query = `INSERT INTO outbox(
id, occurred_at, was_quarantined, topic, payload
) VALUES($1, $2, $3, $4, $5)`;

await this.client.query(query, [
id,
occurredAt,
wasQuarantined,
topic,
payload,
]);
const values = [id, occurredAt, wasQuarantined, topic, payload];
await this.client.query(query, values).catch((error) => {
logger.error(
{ query, values, error },
"PgOutboxRepository_insertEventOnOutbox_QueryErrored",
);
throw error;
});

return { ...event, publications: [] }; // publications will be added after in process
}
Expand Down

0 comments on commit 0bcdaa6

Please sign in to comment.