Skip to content

Commit

Permalink
Justerer validering av notifications (++) (#353)
Browse files Browse the repository at this point in the history
Filterer nå kun ut ugyldige varsler, fremfor å forkaste hele responsen.

Andre endringer:
- Routing for gammel appres ingress
- Routing for trailing slash
  • Loading branch information
anders-nom authored Jul 2, 2024
1 parent d4ea090 commit af798e6
Show file tree
Hide file tree
Showing 7 changed files with 80 additions and 46 deletions.
6 changes: 3 additions & 3 deletions packages/client/src/faro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
* This adds information about decorator parameters to the Grafana faro. To aid with debugging.
* */
export function addFaroMetaData() {
if (!window.faro) return;
if (!window.faro) {
return;
}

window.faro.api.setSession({
attributes: {
decorator_env: JSON.stringify(window.__DECORATOR_DATA__.env),
decorator_params: JSON.stringify(window.__DECORATOR_DATA__.params),
},
});

console.log("Faro: Adding metadata");
}
4 changes: 2 additions & 2 deletions packages/server/src/handlers/auth-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { LogoutIcon } from "decorator-shared/views/icons/logout";
import { match } from "ts-pattern";
import { clientEnv, env } from "../env/server";
import i18n from "../i18n";
import { getNotifications } from "../notifications";
import { fetchNotifications } from "../notifications";
import { AnchorIconButton } from "../views/anchor-icon-button";
import { ArbeidsgiverUserMenuDropdown } from "../views/header/arbeidsgiver-user-menu-dropdown";
import { UserMenuDropdown } from "../views/header/user-menu-dropdown";
Expand Down Expand Up @@ -68,7 +68,7 @@ const buildUsermenuHtml = async (
// @TODO: Tests for important urls, like logout
const template = await match(params.context)
.with("privatperson", async () => {
const notificationsResult = await getNotifications({ cookie });
const notificationsResult = await fetchNotifications({ cookie });

return UserMenuDropdown({
name: auth.name,
Expand Down
2 changes: 1 addition & 1 deletion packages/server/src/handlers/search-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const resultSchema = z.object({
)
.catch((ctx) => {
console.error(
`Error validating search hit - ${ctx.error.message}`,
`Error validating search hit - ${JSON.stringify(ctx.input)}`,
);
return undefined;
}),
Expand Down
22 changes: 20 additions & 2 deletions packages/server/src/notifications.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { env } from "./env/server";
import {
Varsler,
archiveNotification,
getNotifications,
fetchNotifications,
} from "./notifications";
import { expectOK } from "./test-expect";

Expand Down Expand Up @@ -42,6 +42,15 @@ describe("notifications", () => {
tekst: "wat",
link: "http://example.com",
},
{
eventId: "c",
type: "invalidtype",
tidspunkt: "2023-07-05T11:43:02.280367+02:00",
isMasked: false,
eksternVarslingKanaler: ["SMS", "EPOST"],
tekst: "Invalid oppgave",
link: "http://example.com",
},
],
beskjeder: [
{
Expand All @@ -66,7 +75,7 @@ describe("notifications", () => {
afterAll(() => server.close());

test("returns transformed notifications", async () => {
const result = await getNotifications({
const result = await fetchNotifications({
cookie: "cookie",
});

Expand Down Expand Up @@ -108,4 +117,13 @@ describe("notifications", () => {
expectOK(response);
expect(response.data).toEqual("eventId");
});

test("Should filter out invalid notification", async () => {
const response = await fetchNotifications({
cookie: "cookie",
});

expectOK(response);
expect(response.data).not.toContain({ tekst: "Invalid oppgave" });
});
});
83 changes: 49 additions & 34 deletions packages/server/src/notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,31 @@ import { env } from "./env/server";
import { Result, ResultType } from "./result";
import { fetchAndValidateJson } from "./lib/fetch-and-validate";

const varselSchema = z.object({
eventId: z.string(),
type: z.enum(["oppgave", "beskjed", "innboks"]),
tidspunkt: z.string(),
isMasked: z.boolean(),
tekst: z.string().nullable(),
link: z.string().nullable(),
eksternVarslingKanaler: z.array(z.string()),
});
const varselSchema = z
.object({
eventId: z.string(),
type: z.enum(["oppgave", "beskjed", "innboks"]),
tidspunkt: z.string(),
isMasked: z.boolean(),
tekst: z.string().nullable(),
link: z.string().nullable(),
eksternVarslingKanaler: z.array(z.string()),
})
.nullable()
.catch((ctx) => {
console.error(
`Error validating notification - ${JSON.stringify(ctx.input)}`,
);
return null;
});

const varslerSchema = z.object({
oppgaver: z.array(varselSchema),
beskjeder: z.array(varselSchema),
});

type Varsel = z.infer<typeof varselSchema>;
type VarselNullable = z.infer<typeof varselSchema>;
type Varsel = NonNullable<VarselNullable>;

export type Varsler = z.infer<typeof varslerSchema>;

Expand Down Expand Up @@ -50,34 +59,37 @@ const translateNotificationType = {
innboks: "inbox",
};

const sortVarslerNewestFirst = (a: Varsel, b: Varsel) =>
const sortNewestFirst = (a: Varsel, b: Varsel) =>
a.tidspunkt > b.tidspunkt ? -1 : 1;

const filterAndSort = (varsler: VarselNullable[]): Varsel[] =>
varsler
.filter((varsel): varsel is Varsel => !!varsel)
.sort(sortNewestFirst);

const varslerToNotifications = (varsler: Varsler): Notification[] =>
[
varsler.oppgaver.sort(sortVarslerNewestFirst),
varsler.beskjeder.sort(sortVarslerNewestFirst),
].flatMap((list) =>
list.map(
(varsel: Varsel): Notification => ({
id: varsel.eventId,
type: translateNotificationType[
varsel.type
] as NotificationType,
date: varsel.tidspunkt,
channels: varsel.eksternVarslingKanaler,
...(varsel.isMasked
? { masked: true }
: {
masked: false,
text: varsel.tekst ?? "",
link: varsel.link ?? undefined,
}),
}),
),
[filterAndSort(varsler.oppgaver), filterAndSort(varsler.beskjeder)].flatMap(
(list) =>
list.map(
(varsel): Notification => ({
id: varsel.eventId,
type: translateNotificationType[
varsel.type
] as NotificationType,
date: varsel.tidspunkt,
channels: varsel.eksternVarslingKanaler,
...(varsel.isMasked
? { masked: true }
: {
masked: false,
text: varsel.tekst ?? "",
link: varsel.link ?? undefined,
}),
}),
),
);

export const getNotifications = async ({
export const fetchNotifications = async ({
cookie,
}: {
cookie: string;
Expand All @@ -90,7 +102,10 @@ export const getNotifications = async ({
varslerSchema,
).then((result) =>
result.ok
? { ...result, data: varslerToNotifications(result.data) }
? {
...result,
data: varslerToNotifications(result.data as Varsler),
}
: result,
);
};
Expand Down
5 changes: 3 additions & 2 deletions packages/server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { csrAssets } from "./views";
import { MainMenu } from "./views/header/main-menu";
import { texts } from "./texts";
import { clientTextsKeys } from "decorator-shared/types";
import { trimTrailingSlash } from "hono/trailing-slash";

const app = new Hono();

Expand All @@ -34,6 +35,7 @@ if (env.NODE_ENV === "development" || env.IS_LOCAL_PROD) {
}

app.use(headers);
app.use(trimTrailingSlash());

app.get("/public/assets/*", serveStatic({}));

Expand Down Expand Up @@ -164,9 +166,8 @@ app.get("/", async ({ req, html }) => {
});

app.route("/decorator-next", app);
app.route("/decorator-next/", app);
app.route("/dekoratoren", app);
app.route("/dekoratoren/", app);
app.route("/common-html/v4/navno", app);

export default {
...app,
Expand Down
4 changes: 2 additions & 2 deletions packages/server/src/texts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ const nb = {
delskjerm_modal_stengt:
"Skjermdeling er for øyeblikket stengt, prøv igjen senere.",
security_level_info:
"Du har logget inn med Min ID. Hvis du logger inn med et høyere sikkerhetsnivå, får du se mer innhold og flere tjenester.",
"Du har logget inn med MinID. Hvis du logger inn med et høyere sikkerhetsnivå, får du se mer innhold og flere tjenester.",
security_level_link: "Logg inn med BankID, Buypass, eller Commfides.",
go_to_my_page: "Gå til Min side",
my_page: "Min side",
Expand Down Expand Up @@ -179,7 +179,7 @@ const en = {
delskjerm_modal_stengt:
"Screen sharing is currently closed, please try again later.",
security_level_info:
"You are logged in with Min ID. If you log in with a higher security level, you will see more content and additional services.",
"You are logged in with MinID. If you log in with a higher security level, you will see more content and additional services.",
security_level_link: "Log in with BankID, Buypass, or Commfides.",
go_to_my_page: "Go to my page",
my_page: "My page",
Expand Down

0 comments on commit af798e6

Please sign in to comment.