Skip to content

Feature/tanstack db #582

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 25 commits into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions backend/src/lib/docs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import chalk from 'chalk';
import { appConfig } from 'config';
import type { Env } from '#/lib/context';
import { apiModulesList, registerAppSchema } from '#/lib/docs-config';
import { attachmentSelectSchema } from '#/modules/attachments/schema';
import { entityBaseSchema, userSummarySchema } from '#/modules/entities/schema';
import { menuSchema } from '#/modules/me/schema';
import { membershipSummarySchema } from '#/modules/memberships/schema';
Expand Down Expand Up @@ -49,6 +50,7 @@ const docs = async (app: OpenAPIHono<Env>, skipScalar = false) => {
registry.register('MembershipSummarySchema', membershipSummarySchema);
registry.register('MenuSchema', menuSchema);
registry.register('ApiError', errorSchema);
registry.register('AttachmentTableSchema', attachmentSelectSchema);

registerAppSchema(registry);

Expand Down
62 changes: 16 additions & 46 deletions backend/src/modules/attachments/handlers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { OpenAPIHono } from '@hono/zod-openapi';
import { appConfig } from 'config';
import { and, count, eq, ilike, inArray, or, type SQL } from 'drizzle-orm';
import { and, count, eq, inArray } from 'drizzle-orm';
import { html, raw } from 'hono/html';
import { stream } from 'hono/streaming';
import { db } from '#/db/db';
Expand All @@ -17,8 +17,6 @@ import { defaultHook } from '#/utils/default-hook';
import { getIsoDate } from '#/utils/iso-date';
import { logEvent } from '#/utils/logger';
import { nanoid } from '#/utils/nanoid';
import { getOrderColumn } from '#/utils/order-column';
import { prepareStringForILikeFilter } from '#/utils/sql';

const app = new OpenAPIHono<Env>({ defaultHook });

Expand Down Expand Up @@ -119,61 +117,33 @@ const attachmentsRouteHandlers = app
return ctx.json(data, 200);
})
/*
* Get attachments
* Get grouped attachments
*/
.openapi(attachmentRoutes.getAttachments, async (ctx) => {
const { q, sort, order, offset, limit, attachmentId } = ctx.req.valid('query');
.openapi(attachmentRoutes.getAttachmentsGroup, async (ctx) => {
const { mainAttachmentId } = ctx.req.valid('query');

const organization = getContextOrganization();

// Filter at least by valid organization
const filters = [eq(attachmentsTable.organizationId, organization.id)];

if (q) {
const query = prepareStringForILikeFilter(q);
filters.push(or(ilike(attachmentsTable.filename, query), ilike(attachmentsTable.name, query)) as SQL);
// Retrieve target attachment
const [targetAttachment] = await db.select().from(attachmentsTable).where(eq(attachmentsTable.id, mainAttachmentId)).limit(1);
if (!targetAttachment) {
throw new AppError({ status: 404, type: 'not_found', severity: 'warn', entityType: 'attachment', meta: { mainAttachmentId } });
}

const orderColumn = getOrderColumn(
{
id: attachmentsTable.id,
name: attachmentsTable.name,
size: attachmentsTable.size,
createdAt: attachmentsTable.createdAt,
},
sort,
attachmentsTable.id,
order,
);

if (attachmentId) {
// Retrieve target attachment
const [targetAttachment] = await db.select().from(attachmentsTable).where(eq(attachmentsTable.id, attachmentId)).limit(1);
if (!targetAttachment) {
throw new AppError({ status: 404, type: 'not_found', severity: 'warn', entityType: 'attachment', meta: { attachmentId } });
}

const items = await processAttachmentUrlsBatch([targetAttachment]);
// return target attachment itself if no groupId
if (!targetAttachment.groupId) return ctx.json({ items, total: 1 }, 200);
const processedTargetAttachment = await processAttachmentUrlsBatch([targetAttachment]);
// return target attachment itself if no groupId
if (!targetAttachment.groupId) return ctx.json(processedTargetAttachment, 200);

// add filter attachments by groupId
filters.push(eq(attachmentsTable.groupId, targetAttachment.groupId));
}
// add filter attachments by groupId

const attachmentsQuery = db
const attachments = await db
.select()
.from(attachmentsTable)
.where(and(...filters))
.orderBy(orderColumn);

const attachments = await attachmentsQuery.offset(Number(offset)).limit(Number(limit));

const [{ total }] = await db.select({ total: count() }).from(attachmentsQuery.as('attachments'));
.where(and(eq(attachmentsTable.groupId, targetAttachment.groupId), eq(attachmentsTable.organizationId, organization.id)));

const items = await processAttachmentUrlsBatch(attachments);
const processedAttachments = await processAttachmentUrlsBatch(attachments);

return ctx.json({ items, total }, 200);
return ctx.json(processedAttachments, 200);
})
/*
* Get attachment by id
Expand Down
64 changes: 15 additions & 49 deletions backend/src/modules/attachments/routes.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { z } from '@hono/zod-openapi';
import { createCustomRoute } from '#/lib/custom-routes';
import { hasOrgAccess, isAuthenticated, isPublicAccess } from '#/middlewares/guard';
import { attachmentCreateManySchema, attachmentListQuerySchema, attachmentSchema, attachmentUpdateBodySchema } from '#/modules/attachments/schema';
import { attachmentCreateManySchema, attachmentSchema } from '#/modules/attachments/schema';
import { idInOrgParamSchema, idSchema, idsBodySchema, inOrgParamSchema } from '#/utils/schema/common';
import { errorResponses, paginationSchema, successWithRejectedItemsSchema } from '#/utils/schema/responses';
import { errorResponses, successWithRejectedItemsSchema } from '#/utils/schema/responses';

const attachmentRoutes = {
createAttachments: createCustomRoute({
Expand All @@ -28,35 +28,25 @@ const attachmentRoutes = {
responses: {
200: {
description: 'Attachment',
content: {
'application/json': {
schema: z.array(attachmentSchema),
},
},
content: { 'application/json': { schema: z.array(attachmentSchema) } },
},
...errorResponses,
},
}),
getAttachments: createCustomRoute({
operationId: 'getAttachments',

getAttachmentsGroup: createCustomRoute({
operationId: 'getAttachmentsGroup',
method: 'get',
path: '/',
path: '/group',
guard: [isAuthenticated, hasOrgAccess],
tags: ['attachments'],
summary: 'Get list of attachments',
description: 'Retrieves all *attachments* associated with a specific entity, such as an organization.',
request: {
params: inOrgParamSchema,
query: attachmentListQuerySchema,
},
description: 'Retrieves all of *attachments* that are in the same group as main attachment, associated with a specific organization.',
request: { params: inOrgParamSchema, query: z.object({ mainAttachmentId: z.string() }) },
responses: {
200: {
description: 'Attachments',
content: {
'application/json': {
schema: paginationSchema(attachmentSchema),
},
},
content: { 'application/json': { schema: z.array(attachmentSchema) } },
},
...errorResponses,
},
Expand All @@ -75,11 +65,7 @@ const attachmentRoutes = {
responses: {
200: {
description: 'Attachment',
content: {
'application/json': {
schema: attachmentSchema,
},
},
content: { 'application/json': { schema: attachmentSchema } },
},
...errorResponses,
},
Expand All @@ -94,22 +80,12 @@ const attachmentRoutes = {
description: 'Updates metadata of an *attachment*, such as its name or associated entity.',
request: {
params: idInOrgParamSchema,
body: {
content: {
'application/json': {
schema: attachmentUpdateBodySchema,
},
},
},
body: { content: { 'application/json': { schema: attachmentSchema.pick({ name: true }) } } },
},
responses: {
200: {
description: 'Attachment was updated',
content: {
'application/json': {
schema: attachmentSchema,
},
},
content: { 'application/json': { schema: attachmentSchema } },
},
...errorResponses,
},
Expand All @@ -124,22 +100,12 @@ const attachmentRoutes = {
description: 'Deletes one or more *attachment* records by ID. This does not delete the underlying file in storage.',
request: {
params: inOrgParamSchema,
body: {
content: {
'application/json': {
schema: idsBodySchema(),
},
},
},
body: { content: { 'application/json': { schema: idsBodySchema() } } },
},
responses: {
200: {
description: 'Success',
content: {
'application/json': {
schema: successWithRejectedItemsSchema,
},
},
content: { 'application/json': { schema: successWithRejectedItemsSchema } },
},
...errorResponses,
},
Expand Down
9 changes: 1 addition & 8 deletions backend/src/modules/attachments/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { attachmentsTable } from '#/db/schema/attachments';
import { paginationQuerySchema } from '#/utils/schema/common';

const attachmentInsertSchema = createInsertSchema(attachmentsTable);
const attachmentSelectSchema = createSelectSchema(attachmentsTable);
export const attachmentSelectSchema = createSelectSchema(attachmentsTable);

export const attachmentCreateManySchema = z
.array(
Expand All @@ -20,13 +20,6 @@ export const attachmentCreateManySchema = z
.min(1)
.max(50);

export const attachmentUpdateBodySchema = attachmentInsertSchema
.pick({
name: true,
originalKey: true,
})
.partial();

export const attachmentSchema = attachmentSelectSchema.omit({ originalKey: true, convertedKey: true, thumbnailKey: true }).extend({
url: z.string(),
thumbnailUrl: z.string().nullable(),
Expand Down
3 changes: 3 additions & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,10 @@
"@sentry/react": "^9.44.0",
"@t3-oss/env-core": "^0.13.8",
"@tailwindcss/typography": "^0.5.16",
"@tanstack/electric-db-collection": "^0.1.1",
"@tanstack/query-db-collection": "^0.2.0",
"@tanstack/query-sync-storage-persister": "^5.83.1",
"@tanstack/react-db": "^0.1.1",
"@tanstack/react-query": "^5.84.1",
"@tanstack/react-query-devtools": "^5.84.1",
"@tanstack/react-query-persist-client": "^5.84.1",
Expand Down
Loading