Skip to content

Open-source status page, incident response and uptime monitoring

🚀 create notification api (#716)

Thibault Le Ouay3142372c16a3
diff --git a/apps/server/package.json b/apps/server/package.json
index 510a04dc0..91ef7d497 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -28,10 +28,12 @@
"@unkey/api": "0.16.0",
"hono": "4.0.0",
"nanoid": "5.0.2",
+ "validator": "13.11.0",
"zod": "3.22.2"
},
"devDependencies": {
"@openstatus/tsconfig": "workspace:*",
+ "@types/validator": "13.11.6",
"bun-types": "1.0.11",
"dotenv": "16.3.1",
"eslint": "8.50.0"
diff --git a/apps/server/src/v1/index.ts b/apps/server/src/v1/index.ts
index 80af6891a..86780e64a 100644
--- a/apps/server/src/v1/index.ts
+++ b/apps/server/src/v1/index.ts
@@ -7,6 +7,7 @@ import type { Limits } from "@openstatus/plans/src/types";
import { incidentsApi } from "./incidents";
import { middleware } from "./middleware";
import { monitorApi } from "./monitor";
+import { notificationApi } from "./notification";
import { pageApi } from "./page";
import { statusReportApi } from "./statusReport";
import { statusReportUpdateApi } from "./statusReportUpdate";
@@ -36,9 +37,10 @@ api.doc("/openapi", {
*/
api.use("/*", middleware);
api.use("/*", logger());
-api.route("/monitor", monitorApi);
-api.route("/status_report_update", statusReportUpdateApi);
api.route("/incident", incidentsApi);
+api.route("/monitor", monitorApi);
+api.route("/notification", notificationApi);
api.route("/page", pageApi);
api.route("/status_report", statusReportApi);
+api.route("/status_report_update", statusReportUpdateApi);
diff --git a/apps/server/src/v1/notification.test.ts b/apps/server/src/v1/notification.test.ts
new file mode 100644
index 000000000..2617a162f
--- /dev/null
+++ b/apps/server/src/v1/notification.test.ts
@@ -0,0 +1,27 @@
+import { expect, test } from "bun:test";
+
+import { api } from ".";
+import { iso8601Regex } from "./test-utils";
+
+test.only("Create a notification", async () => {
+ const data = {
+ name: "OpenStatus",
+ provider: "email",
+ payload: { email: "[email protected]" },
+ };
+ const res = await api.request("/notification", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify(data),
+ });
+ expect(res.status).toBe(200);
+
+ expect(await res.json()).toMatchObject({
+ id: expect.any(Number),
+ provider: "email",
+ payload: { email: "[email protected]" },
+ });
+});
diff --git a/apps/server/src/v1/notification.ts b/apps/server/src/v1/notification.ts
new file mode 100644
index 000000000..380c123bf
--- /dev/null
+++ b/apps/server/src/v1/notification.ts
@@ -0,0 +1,239 @@
+import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
+import isEmail from "validator/lib/isEmail";
+import isMobilePhone from "validator/lib/isMobilePhone";
+
+import { and, db, eq, inArray } from "@openstatus/db";
+import {
+ monitor,
+ notification,
+ NotificationDataSchema,
+ notificationProvider,
+ notificationsToMonitors,
+ page,
+ selectNotificationSchema,
+} from "@openstatus/db/src/schema";
+
+import type { Variables } from ".";
+import { ErrorSchema } from "./shared";
+
+const notificationApi = new OpenAPIHono<{ Variables: Variables }>();
+
+const ParamsSchema = z.object({
+ id: z
+ .string()
+ .min(1)
+ .openapi({
+ param: {
+ name: "id",
+ in: "path",
+ },
+ description: "The id of the notification",
+ example: "1",
+ }),
+});
+
+const NotificationSchema = z.object({
+ id: z
+ .number()
+ .openapi({ description: "The id of the notification", example: 1 }),
+ name: z.string().openapi({
+ description: "The name of the notification",
+ example: "OpenStatus Discord",
+ }),
+ provider: z.enum(notificationProvider).openapi({
+ description: "The provider of the notification",
+ example: "discord",
+ }),
+ payload: NotificationDataSchema.openapi({
+ description: "The data of the notification",
+ examples: [
+ { email: "[email protected]" },
+ { discord: "https://discord.com/api/webhooks/{channelId}/xxx..." },
+ ],
+ }),
+ monitors: z
+ .array(z.number())
+ .openapi({
+ description: "The monitors that the notification is linked to",
+ example: [1, 2],
+ })
+ .nullish(),
+});
+
+const CreateNotificationSchema = z.object({
+ name: z.string().openapi({
+ description: "The name of the notification",
+ example: "OpenStatus Discord",
+ }),
+ provider: z.enum(notificationProvider).openapi({
+ description: "The provider of the notification",
+ example: "discord",
+ }),
+ payload: NotificationDataSchema.openapi({
+ description: "The data of the notification",
+ examples: [
+ { email: "[email protected]" },
+ { discord: "https://discord.com/api/webhooks/{channelId}/xxx..." },
+ ],
+ }),
+ monitors: z
+ .array(z.number())
+ .openapi({
+ description: "The monitors that the notification is linked to",
+ example: [1, 2],
+ })
+ .nullish(),
+});
+const getRoute = createRoute({
+ method: "get",
+ tags: ["notification"],
+ description: "Get a notification",
+ path: "/:id",
+ request: {
+ params: ParamsSchema,
+ },
+ responses: {
+ 200: {
+ content: {
+ "application/json": {
+ schema: NotificationSchema,
+ },
+ },
+ description: "Get an Status page",
+ },
+ 400: {
+ content: {
+ "application/json": {
+ schema: ErrorSchema,
+ },
+ },
+ description: "Returns an error",
+ },
+ },
+});
+
+notificationApi.openapi(getRoute, async (c) => {
+ const workspaceId = Number(c.get("workspaceId"));
+ const { id } = c.req.valid("param");
+
+ const notificationId = Number(id);
+ const result = await db
+ .select()
+ .from(notification)
+ .where(
+ and(
+ eq(page.workspaceId, workspaceId),
+ eq(notification.id, notificationId),
+ ),
+ )
+ .get();
+
+ if (!result) return c.json({ code: 404, message: "Not Found" }, 404);
+ const linkedMonitors = await db
+ .select()
+ .from(notificationsToMonitors)
+ .where(eq(notificationsToMonitors.notificationId, notificationId))
+ .all();
+
+ const monitorsId = linkedMonitors.map((m) => m.monitorId);
+
+ const data = NotificationSchema.parse({
+ ...result,
+ payload: JSON.parse(result.data || "{}"),
+ monitors: monitorsId,
+ });
+
+ return c.json(data);
+});
+
+const postRoute = createRoute({
+ method: "post",
+ tags: ["page"],
+ description: "Create a notification",
+ path: "/",
+ request: {
+ body: {
+ description: "The notification to create",
+ content: {
+ "application/json": {
+ schema: CreateNotificationSchema,
+ },
+ },
+ },
+ },
+ responses: {
+ 200: {
+ content: {
+ "application/json": {
+ schema: NotificationSchema,
+ },
+ },
+ description: "Return the created notification",
+ },
+ 400: {
+ content: {
+ "application/json": {
+ schema: ErrorSchema,
+ },
+ },
+ description: "Returns an error",
+ },
+ },
+});
+
+notificationApi.openapi(postRoute, async (c) => {
+ const workspaceId = Number(c.get("workspaceId"));
+ const workspacePlan = c.get("workspacePlan");
+ const input = c.req.valid("json");
+ console.log(input);
+ if (input.provider === "sms" && workspacePlan.title === "free") {
+ return c.json({ code: 403, message: "Forbidden" }, 403);
+ }
+
+ const { payload, monitors, ...rest } = input;
+ if (monitors) {
+ const monitorsData = await db
+ .select()
+ .from(monitor)
+ .where(
+ and(
+ inArray(monitor.id, monitors),
+ eq(monitor.workspaceId, workspaceId),
+ ),
+ )
+ .all();
+ if (monitorsData.length !== monitors.length)
+ return c.json({ code: 400, message: "Monitor not found" }, 400);
+ }
+
+ const newNotif = await db
+ .insert(notification)
+ .values({
+ workspaceId,
+ ...rest,
+ data: JSON.stringify(payload),
+ })
+ .returning()
+ .get();
+
+ console.log(newNotif);
+ if (monitors) {
+ for (const monitorId of monitors) {
+ await db
+ .insert(notificationsToMonitors)
+ .values({ notificationId: newNotif.id, monitorId })
+ .run();
+ }
+ }
+ const d = selectNotificationSchema.parse(newNotif);
+
+ const p = NotificationDataSchema.parse(JSON.parse(d.data));
+ const data = NotificationSchema.parse({
+ ...newNotif,
+ monitors: monitors,
+ payload: p,
+ });
+ return c.json(data);
+});
+
+export { notificationApi };
diff --git a/apps/server/src/v1/page.ts b/apps/server/src/v1/page.ts
index e9abe8eee..b4f39dfe7 100644
--- a/apps/server/src/v1/page.ts
+++ b/apps/server/src/v1/page.ts
@@ -1,6 +1,6 @@
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
-import { and, desc, eq, inArray, sql } from "@openstatus/db";
+import { and, eq, inArray, sql } from "@openstatus/db";
import { db } from "@openstatus/db/src/db";
import {
monitor,
@@ -314,7 +314,7 @@ const postRoute = createRoute({
path: "/",
request: {
body: {
- description: "The monitor to create",
+ description: "The status page to create",
content: {
"application/json": {
schema: CreatePageSchema,
diff --git a/packages/db/src/schema/notifications/validation.ts b/packages/db/src/schema/notifications/validation.ts
index 16a741dfd..1362a1df9 100644
--- a/packages/db/src/schema/notifications/validation.ts
+++ b/packages/db/src/schema/notifications/validation.ts
@@ -26,3 +26,18 @@ export const insertNotificationSchema = createInsertSchema(notification).extend(
export type InsertNotification = z.infer<typeof insertNotificationSchema>;
export type Notification = z.infer<typeof selectNotificationSchema>;
export type NotificationProvider = z.infer<typeof notificationProviderSchema>;
+
+export const NotificationDataSchema = z.union([
+ z.object({
+ sms: z.string(),
+ }),
+ z.object({
+ email: z.string().email(),
+ }),
+ z.object({
+ slack: z.string(),
+ }),
+ z.object({
+ discord: z.string(),
+ }),
+]);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c095ae7f0..a4a285dca 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -88,6 +88,9 @@ importers:
nanoid:
specifier: 5.0.2
version: 5.0.2
+ validator:
+ specifier: 13.11.0
+ version: 13.11.0
zod:
specifier: 3.22.2
version: 3.22.2
@@ -95,6 +98,9 @@ importers:
'@openstatus/tsconfig':
specifier: workspace:*
version: link:../../packages/tsconfig
+ '@types/validator':
+ specifier: 13.11.6
+ version: 13.11.6
bun-types:
specifier: 1.0.11
version: 1.0.11
@@ -1392,10 +1398,6 @@ packages:
peerDependencies:
'@effect-ts/otel-node': '*'
peerDependenciesMeta:
- '@effect-ts/core':
- optional: true
- '@effect-ts/otel':
- optional: true
'@effect-ts/otel-node':
optional: true
dependencies:
@@ -5409,7 +5411,6 @@ packages:
resolution: {integrity: sha512-HUgHujPhKuNzgNXBRZKYexwoG+gHKU+tnfPqjWXFghZAnn73JElicMkuSKJyLGr9JgyA8IgK7fj88IyA9rwYeQ==}
- dev: false
resolution: {integrity: sha512-flUksGIQCnJd6sZ1l5dqCEG/ksaoAg/eUwiLAGTJQcfgvZJKF++Ta4bJA6A5aPSJmsr+xlseHn4KLgVlNnvPTg==}