refactor(api): ♻️ More OpenAPI refactoring

This commit is contained in:
Jesse Wierzbinski 2024-09-15 14:59:21 +02:00
parent b755fc5d62
commit 739bbe935b
No known key found for this signature in database
7 changed files with 471 additions and 297 deletions

View file

@ -1,9 +1,10 @@
import { apiRoute, applyConfig, auth, handleZodError } from "@/api"; import { apiRoute, applyConfig, auth } from "@/api";
import { zValidator } from "@hono/zod-validator"; import { createRoute } from "@hono/zod-openapi";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { z } from "zod"; import { z } from "zod";
import { db } from "~/drizzle/db"; import { db } from "~/drizzle/db";
import { Notifications, RolePermissions } from "~/drizzle/schema"; import { Notifications, RolePermissions } from "~/drizzle/schema";
import { ErrorSchema } from "~/types/api";
export const meta = applyConfig({ export const meta = applyConfig({
allowedMethods: ["POST"], allowedMethods: ["POST"],
@ -27,13 +28,31 @@ export const schemas = {
}), }),
}; };
const route = createRoute({
method: "post",
path: "/api/v1/notifications/{id}/dismiss",
summary: "Dismiss notification",
middleware: [auth(meta.auth, meta.permissions)],
request: {
params: schemas.param,
},
responses: {
200: {
description: "Notification dismissed",
},
401: {
description: "Unauthorized",
content: {
"application/json": {
schema: ErrorSchema,
},
},
},
},
});
export default apiRoute((app) => export default apiRoute((app) =>
app.on( app.openapi(route, async (context) => {
meta.allowedMethods,
meta.route,
zValidator("param", schemas.param, handleZodError),
auth(meta.auth, meta.permissions),
async (context) => {
const { id } = context.req.valid("param"); const { id } = context.req.valid("param");
const { user } = context.get("auth"); const { user } = context.get("auth");
@ -48,7 +67,6 @@ export default apiRoute((app) =>
}) })
.where(eq(Notifications.id, id)); .where(eq(Notifications.id, id));
return context.json({}); return context.newResponse(null, 200);
}, }),
),
); );

View file

@ -1,8 +1,14 @@
import { apiRoute, applyConfig, auth, handleZodError } from "@/api"; import { apiRoute, applyConfig, auth } from "@/api";
import { zValidator } from "@hono/zod-validator"; import { createRoute } from "@hono/zod-openapi";
import { z } from "zod"; import { z } from "zod";
import { findManyNotifications } from "~/classes/functions/notification"; import {
findManyNotifications,
notificationToApi,
} from "~/classes/functions/notification";
import { RolePermissions } from "~/drizzle/schema"; import { RolePermissions } from "~/drizzle/schema";
import { Note } from "~/packages/database-interface/note";
import { User } from "~/packages/database-interface/user";
import { ErrorSchema } from "~/types/api";
export const meta = applyConfig({ export const meta = applyConfig({
allowedMethods: ["GET"], allowedMethods: ["GET"],
@ -26,13 +32,69 @@ export const schemas = {
}), }),
}; };
const route = createRoute({
method: "get",
path: "/api/v1/notifications/{id}",
summary: "Get notification",
middleware: [auth(meta.auth, meta.permissions)],
request: {
params: schemas.param,
},
responses: {
200: {
description: "Notification",
schema: z.object({
account: z.lazy(() => User.schema).nullable(),
created_at: z.string(),
id: z.string().uuid(),
status: z.lazy(() => Note.schema).optional(),
// TODO: Add reactions
type: z.enum([
"mention",
"status",
"follow",
"follow_request",
"reblog",
"poll",
"favourite",
"update",
"admin.sign_up",
"admin.report",
"chat",
"pleroma:chat_mention",
"pleroma:emoji_reaction",
"pleroma:event_reminder",
"pleroma:participation_request",
"pleroma:participation_accepted",
"move",
"group_reblog",
"group_favourite",
"user_approved",
]),
target: z.lazy(() => User.schema).optional(),
}),
},
401: {
description: "Unauthorized",
content: {
"application/json": {
schema: ErrorSchema,
},
},
},
404: {
description: "Notification not found",
content: {
"application/json": {
schema: ErrorSchema,
},
},
},
},
});
export default apiRoute((app) => export default apiRoute((app) =>
app.on( app.openapi(route, async (context) => {
meta.allowedMethods,
meta.route,
zValidator("param", schemas.param, handleZodError),
auth(meta.auth, meta.permissions),
async (context) => {
const { id } = context.req.valid("param"); const { id } = context.req.valid("param");
const { user } = context.get("auth"); const { user } = context.get("auth");
@ -43,8 +105,7 @@ export default apiRoute((app) =>
const notification = ( const notification = (
await findManyNotifications( await findManyNotifications(
{ {
where: (notification, { eq }) => where: (notification, { eq }) => eq(notification.id, id),
eq(notification.id, id),
limit: 1, limit: 1,
}, },
user.id, user.id,
@ -55,7 +116,6 @@ export default apiRoute((app) =>
return context.json({ error: "Notification not found" }, 404); return context.json({ error: "Notification not found" }, 404);
} }
return context.json(notification); return context.json(await notificationToApi(notification), 200);
}, }),
),
); );

View file

@ -1,7 +1,9 @@
import { apiRoute, applyConfig, auth } from "@/api"; import { apiRoute, applyConfig, auth } from "@/api";
import { createRoute } from "@hono/zod-openapi";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { db } from "~/drizzle/db"; import { db } from "~/drizzle/db";
import { Notifications, RolePermissions } from "~/drizzle/schema"; import { Notifications, RolePermissions } from "~/drizzle/schema";
import { ErrorSchema } from "~/types/api";
export const meta = applyConfig({ export const meta = applyConfig({
allowedMethods: ["POST"], allowedMethods: ["POST"],
@ -19,12 +21,28 @@ export const meta = applyConfig({
}, },
}); });
const route = createRoute({
method: "post",
path: "/api/v1/notifications/clear",
summary: "Clear notifications",
middleware: [auth(meta.auth, meta.permissions)],
responses: {
200: {
description: "Notifications cleared",
},
401: {
description: "Unauthorized",
content: {
"application/json": {
schema: ErrorSchema,
},
},
},
},
});
export default apiRoute((app) => export default apiRoute((app) =>
app.on( app.openapi(route, async (context) => {
meta.allowedMethods,
meta.route,
auth(meta.auth, meta.permissions),
async (context) => {
const { user } = context.get("auth"); const { user } = context.get("auth");
if (!user) { if (!user) {
return context.json({ error: "Unauthorized" }, 401); return context.json({ error: "Unauthorized" }, 401);
@ -37,7 +55,6 @@ export default apiRoute((app) =>
}) })
.where(eq(Notifications.notifiedId, user.id)); .where(eq(Notifications.notifiedId, user.id));
return context.json({}); return context.newResponse(null, 200);
}, }),
),
); );

View file

@ -1,9 +1,10 @@
import { apiRoute, applyConfig, auth, handleZodError } from "@/api"; import { apiRoute, applyConfig, auth } from "@/api";
import { zValidator } from "@hono/zod-validator"; import { createRoute } from "@hono/zod-openapi";
import { and, eq, inArray } from "drizzle-orm"; import { and, eq, inArray } from "drizzle-orm";
import { z } from "zod"; import { z } from "zod";
import { db } from "~/drizzle/db"; import { db } from "~/drizzle/db";
import { Notifications, RolePermissions } from "~/drizzle/schema"; import { Notifications, RolePermissions } from "~/drizzle/schema";
import { ErrorSchema } from "~/types/api";
export const meta = applyConfig({ export const meta = applyConfig({
allowedMethods: ["DELETE"], allowedMethods: ["DELETE"],
@ -27,13 +28,31 @@ export const schemas = {
}), }),
}; };
const route = createRoute({
method: "delete",
path: "/api/v1/notifications/destroy_multiple",
summary: "Dismiss multiple notifications",
middleware: [auth(meta.auth, meta.permissions)],
request: {
query: schemas.query,
},
responses: {
200: {
description: "Notifications dismissed",
},
401: {
description: "Unauthorized",
content: {
"application/json": {
schema: ErrorSchema,
},
},
},
},
});
export default apiRoute((app) => export default apiRoute((app) =>
app.on( app.openapi(route, async (context) => {
meta.allowedMethods,
meta.route,
zValidator("query", schemas.query, handleZodError),
auth(meta.auth, meta.permissions),
async (context) => {
const { user } = context.get("auth"); const { user } = context.get("auth");
if (!user) { if (!user) {
@ -54,7 +73,6 @@ export default apiRoute((app) =>
), ),
); );
return context.json({}); return context.newResponse(null, 200);
}, }),
),
); );

View file

@ -1,12 +1,6 @@
import { import { apiRoute, applyConfig, auth, idValidator } from "@/api";
apiRoute,
applyConfig,
auth,
handleZodError,
idValidator,
} from "@/api";
import { fetchTimeline } from "@/timelines"; import { fetchTimeline } from "@/timelines";
import { zValidator } from "@hono/zod-validator"; import { createRoute } from "@hono/zod-openapi";
import { sql } from "drizzle-orm"; import { sql } from "drizzle-orm";
import { z } from "zod"; import { z } from "zod";
import { import {
@ -15,6 +9,9 @@ import {
} from "~/classes/functions/notification"; } from "~/classes/functions/notification";
import type { NotificationWithRelations } from "~/classes/functions/notification"; import type { NotificationWithRelations } from "~/classes/functions/notification";
import { RolePermissions } from "~/drizzle/schema"; import { RolePermissions } from "~/drizzle/schema";
import { Note } from "~/packages/database-interface/note";
import { User } from "~/packages/database-interface/user";
import { ErrorSchema } from "~/types/api";
export const meta = applyConfig({ export const meta = applyConfig({
allowedMethods: ["GET"], allowedMethods: ["GET"],
@ -36,7 +33,8 @@ export const meta = applyConfig({
}); });
export const schemas = { export const schemas = {
query: z.object({ query: z
.object({
max_id: z.string().regex(idValidator).optional(), max_id: z.string().regex(idValidator).optional(),
since_id: z.string().regex(idValidator).optional(), since_id: z.string().regex(idValidator).optional(),
min_id: z.string().regex(idValidator).optional(), min_id: z.string().regex(idValidator).optional(),
@ -92,16 +90,53 @@ export const schemas = {
.array() .array()
.optional(), .optional(),
account_id: z.string().regex(idValidator).optional(), account_id: z.string().regex(idValidator).optional(),
})
.refine((val) => {
// Can't use both exclude_types and types
return !(val.exclude_types && val.types);
}), }),
}; };
const route = createRoute({
method: "get",
path: "/api/v1/notifications",
summary: "Get notifications",
middleware: [auth(meta.auth, meta.permissions)],
request: {
query: schemas.query,
},
responses: {
200: {
description: "Notifications",
content: {
"application/json": {
schema: z.array(
z.object({
account: z.lazy(() => User.schema).nullable(),
created_at: z.string(),
id: z.string().uuid(),
status: z.lazy(() => Note.schema).optional(),
// TODO: Add reactions
type: z.string(),
target: z.lazy(() => User.schema).optional(),
}),
),
},
},
},
401: {
description: "Unauthorized",
content: {
"application/json": {
schema: ErrorSchema,
},
},
},
},
});
export default apiRoute((app) => export default apiRoute((app) =>
app.on( app.openapi(route, async (context) => {
meta.allowedMethods,
meta.route,
zValidator("query", schemas.query, handleZodError),
auth(meta.auth, meta.permissions),
async (context) => {
const { user } = context.get("auth"); const { user } = context.get("auth");
if (!user) { if (!user) {
return context.json({ error: "Unauthorized" }, 401); return context.json({ error: "Unauthorized" }, 401);
@ -117,15 +152,6 @@ export default apiRoute((app) =>
types, types,
} = context.req.valid("query"); } = context.req.valid("query");
if (types && exclude_types) {
return context.json(
{
error: "Can't use both types and exclude_types",
},
400,
);
}
const { objects, link } = const { objects, link } =
await fetchTimeline<NotificationWithRelations>( await fetchTimeline<NotificationWithRelations>(
findManyNotifications, findManyNotifications,
@ -137,15 +163,11 @@ export default apiRoute((app) =>
{ lt, gte, gt, and, eq, not, inArray }, { lt, gte, gt, and, eq, not, inArray },
) => ) =>
and( and(
max_id max_id ? lt(notification.id, max_id) : undefined,
? lt(notification.id, max_id)
: undefined,
since_id since_id
? gte(notification.id, since_id) ? gte(notification.id, since_id)
: undefined, : undefined,
min_id min_id ? gt(notification.id, min_id) : undefined,
? gt(notification.id, min_id)
: undefined,
eq(notification.notifiedId, user.id), eq(notification.notifiedId, user.id),
eq(notification.dismissed, false), eq(notification.dismissed, false),
account_id account_id
@ -156,12 +178,7 @@ export default apiRoute((app) =>
? inArray(notification.type, types) ? inArray(notification.type, types)
: undefined, : undefined,
exclude_types exclude_types
? not( ? not(inArray(notification.type, exclude_types))
inArray(
notification.type,
exclude_types,
),
)
: undefined, : undefined,
// Don't show notes that have filtered words in them (via Notification.note.content via Notification.noteId) // Don't show notes that have filtered words in them (via Notification.note.content via Notification.noteId)
// Filters in `Filters` table have keyword in `FilterKeywords` table (use LIKE) // Filters in `Filters` table have keyword in `FilterKeywords` table (use LIKE)
@ -185,8 +202,7 @@ export default apiRoute((app) =>
), ),
limit, limit,
// @ts-expect-error Yes I KNOW the types are wrong // @ts-expect-error Yes I KNOW the types are wrong
orderBy: (notification, { desc }) => orderBy: (notification, { desc }) => desc(notification.id),
desc(notification.id),
}, },
context.req.raw, context.req.raw,
user.id, user.id,
@ -199,6 +215,5 @@ export default apiRoute((app) =>
Link: link, Link: link,
}, },
); );
}, }),
),
); );

View file

@ -1,5 +1,8 @@
import { apiRoute, applyConfig, auth } from "@/api"; import { apiRoute, applyConfig, auth } from "@/api";
import { createRoute } from "@hono/zod-openapi";
import { RolePermissions } from "~/drizzle/schema"; import { RolePermissions } from "~/drizzle/schema";
import { User } from "~/packages/database-interface/user";
import { ErrorSchema } from "~/types/api";
export const meta = applyConfig({ export const meta = applyConfig({
allowedMethods: ["DELETE"], allowedMethods: ["DELETE"],
@ -16,12 +19,33 @@ export const meta = applyConfig({
}, },
}); });
const route = createRoute({
method: "delete",
path: "/api/v1/profile/avatar",
summary: "Delete avatar",
middleware: [auth(meta.auth, meta.permissions)],
responses: {
200: {
description: "User",
content: {
"application/json": {
schema: User.schema,
},
},
},
401: {
description: "Unauthorized",
content: {
"application/json": {
schema: ErrorSchema,
},
},
},
},
});
export default apiRoute((app) => export default apiRoute((app) =>
app.on( app.openapi(route, async (context) => {
meta.allowedMethods,
meta.route,
auth(meta.auth, meta.permissions),
async (context) => {
const { user: self } = context.get("auth"); const { user: self } = context.get("auth");
if (!self) { if (!self) {
@ -32,7 +56,6 @@ export default apiRoute((app) =>
avatar: "", avatar: "",
}); });
return context.json(self.toApi(true)); return context.json(self.toApi(true), 200);
}, }),
),
); );

View file

@ -1,5 +1,8 @@
import { apiRoute, applyConfig, auth } from "@/api"; import { apiRoute, applyConfig, auth } from "@/api";
import { createRoute } from "@hono/zod-openapi";
import { RolePermissions } from "~/drizzle/schema"; import { RolePermissions } from "~/drizzle/schema";
import { User } from "~/packages/database-interface/user";
import { ErrorSchema } from "~/types/api";
export const meta = applyConfig({ export const meta = applyConfig({
allowedMethods: ["DELETE"], allowedMethods: ["DELETE"],
@ -16,12 +19,33 @@ export const meta = applyConfig({
}, },
}); });
const route = createRoute({
method: "delete",
path: "/api/v1/profile/header",
summary: "Delete header",
middleware: [auth(meta.auth, meta.permissions)],
responses: {
200: {
description: "User",
content: {
"application/json": {
schema: User.schema,
},
},
},
401: {
description: "Unauthorized",
content: {
"application/json": {
schema: ErrorSchema,
},
},
},
},
});
export default apiRoute((app) => export default apiRoute((app) =>
app.on( app.openapi(route, async (context) => {
meta.allowedMethods,
meta.route,
auth(meta.auth, meta.permissions),
async (context) => {
const { user: self } = context.get("auth"); const { user: self } = context.get("auth");
if (!self) { if (!self) {
@ -32,7 +56,6 @@ export default apiRoute((app) =>
header: "", header: "",
}); });
return context.json(self.toApi(true)); return context.json(self.toApi(true), 200);
}, }),
),
); );