Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 5 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ jobs:
image: redis:7-alpine
ports:
- 6379:6379
options: >-
--health-cmd "redis-cli ping"
--health-interval 5s
--health-timeout 5s
--health-retries 5

steps:
- uses: actions/checkout@v4
Expand Down
35 changes: 27 additions & 8 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "linkforge",
"version": "0.3.0",
"version": "0.4.0",
"description": "URL shortener API with authentication, API keys, async click tracking and analytics.",
"type": "module",
"license": "MIT",
Expand Down Expand Up @@ -38,6 +38,7 @@
"fastify": "^5.8.5",
"ioredis": "^5.10.1",
"jose": "^6.2.3",
"nanoid": "^5.1.11",
"pg": "^8.21.0",
"pino": "^10.3.1",
"zod": "^4.4.3"
Expand Down
22 changes: 22 additions & 0 deletions prisma/migrations/20260526160925_links_model/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
-- CreateTable
CREATE TABLE "links" (
"id" UUID NOT NULL,
"code" TEXT NOT NULL,
"target" TEXT NOT NULL,
"userId" UUID NOT NULL,
"expiresAt" TIMESTAMP(3),
"deletedAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,

CONSTRAINT "links_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "links_code_key" ON "links"("code");

-- CreateIndex
CREATE INDEX "links_userId_createdAt_id_idx" ON "links"("userId", "createdAt", "id");

-- AddForeignKey
ALTER TABLE "links" ADD CONSTRAINT "links_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
17 changes: 17 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ model User {

refreshTokens RefreshToken[]
apiKeys ApiKey[]
links Link[]

@@map("users")
}
Expand Down Expand Up @@ -46,4 +47,20 @@ model ApiKey {

@@index([userId])
@@map("api_keys")
}

model Link {
id String @id @default(uuid()) @db.Uuid
code String @unique
target String
userId String @db.Uuid
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
expiresAt DateTime?
deletedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

// Cursor pagination scans by (userId, createdAt, id).
@@index([userId, createdAt, id])
@@map("links")
}
2 changes: 2 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { registerErrorHandler } from '@/shared/errors/error-handler';
import { healthRoutes } from '@/modules/health/health.routes';
import { authRoutes } from './modules/auth/auth.routes';
import { apiKeyRoutes } from './modules/api-keys/api-keys.routes';
import { linkRoutes } from './modules/links/links.routes';

/**
* Builds a fully configured Fastify instance without starting the server.
Expand All @@ -30,6 +31,7 @@ export async function buildApp(): Promise<FastifyInstance> {
(v1) => {
v1.register(authRoutes);
v1.register(apiKeyRoutes);
v1.register(linkRoutes);
},
{ prefix: '/v1' },
);
Expand Down
45 changes: 45 additions & 0 deletions src/modules/links/links.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import type { FastifyReply, FastifyRequest } from 'fastify';
import { getAuth } from '@/shared/middleware/authenticate';
import { getIdempotencyKey } from '@/shared/middleware/idempotency';
import type { LinksService } from './links.service';
import {
createLinkSchema,
linkIdParamsSchema,
listLinksQuerySchema,
updateLinkSchema,
} from './links.schemas';

export function createLinksController(service: LinksService) {
return {
create: async (request: FastifyRequest, reply: FastifyReply) => {
const { userId } = getAuth(request);
const input = createLinkSchema.parse(request.body);
const link = await service.create({
userId,
input,
idempotencyKey: getIdempotencyKey(request),
});
return reply.status(201).send(link);
},

list: async (request: FastifyRequest, reply: FastifyReply) => {
const { userId } = getAuth(request);
const { cursor, limit } = listLinksQuerySchema.parse(request.query);
return reply.send(await service.list(userId, limit, cursor));
},

update: async (request: FastifyRequest, reply: FastifyReply) => {
const { userId } = getAuth(request);
const { id } = linkIdParamsSchema.parse(request.params);
const input = updateLinkSchema.parse(request.body);
return reply.send(await service.update(userId, id, input));
},

remove: async (request: FastifyRequest, reply: FastifyReply) => {
const { userId } = getAuth(request);
const { id } = linkIdParamsSchema.parse(request.params);
await service.remove(userId, id);
return reply.status(204).send();
},
};
}
69 changes: 69 additions & 0 deletions src/modules/links/links.repository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import type { Prisma, PrismaClient } from '@prisma/client';

export function createLinksRepository(db: PrismaClient) {
return {
findByCode(code: string) {
return db.link.findFirst({
where: {
code,
deletedAt: null,
},
});
},

findById(id: string) {
return db.link.findFirst({
where: {
id,
deletedAt: null,
},
});
},

create(data: { code: string; target: string; userId: string; expiresAt?: Date | null }) {
return db.link.create({
data,
});
},

/** Cursor pagination: fetch limit+1 to detect whether another page exists. */
listByUser(userId: string, limit: number, cursorId?: string) {
return db.link.findMany({
where: {
userId,
deletedAt: null,
},

orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],

take: limit + 1,

...(cursorId
? {
cursor: { id: cursorId },
skip: 1,
}
: {}),
});
},

update(id: string, data: Prisma.LinkUpdateInput) {
return db.link.update({
where: { id },
data,
});
},

softDelete(id: string) {
return db.link.update({
where: { id },

data: {
deletedAt: new Date(),
},
});
},
};
}

export type LinksRepository = ReturnType<typeof createLinksRepository>;
20 changes: 20 additions & 0 deletions src/modules/links/links.routes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import type { FastifyInstance } from 'fastify';
import { prisma } from '@/shared/db';
import { redis } from '@/shared/cache/redis';
import { createCacheService } from '@/shared/cache/cache.service';
import { authenticate, requireScope } from '@/shared/middleware/authenticate';
import { createLinksRepository } from './links.repository';
import { createLinksService } from './links.service';
import { createLinksController } from './links.controller';

export function linkRoutes(app: FastifyInstance): void {
const service = createLinksService(createLinksRepository(prisma), createCacheService(redis));
const controller = createLinksController(service);

app.addHook('preHandler', authenticate);

app.post('/links', { preHandler: requireScope('write') }, controller.create);
app.get('/links', { preHandler: requireScope('read') }, controller.list);
app.patch('/links/:id', { preHandler: requireScope('write') }, controller.update);
app.delete('/links/:id', { preHandler: requireScope('write') }, controller.remove);
}
30 changes: 30 additions & 0 deletions src/modules/links/links.schemas.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { z } from 'zod';

const slugPattern = /^[a-zA-Z0-9_-]{3,30}$/;

export const createLinkSchema = z.object({
target: z.url(),
customSlug: z
.string()
.regex(slugPattern, 'Slug must be 3-30 chars: a-z, A-Z, 0-9, _ or -')
.optional(),
expiresAt: z.iso.datetime().optional(),
});

export const updateLinkSchema = z
.object({
target: z.url().optional(),
expiresAt: z.iso.datetime().nullable().optional(),
})
.refine((data) => Object.keys(data).length > 0, { error: 'At least one field is required' });

export const listLinksQuerySchema = z.object({
cursor: z.string().optional(),
limit: z.coerce.number().int().min(1).max(100).default(20),
});

export const linkIdParamsSchema = z.object({ id: z.uuid() });

export type CreateLinkInput = z.infer<typeof createLinkSchema>;
export type UpdateLinkInput = z.infer<typeof updateLinkSchema>;
export type ListLinksQuery = z.infer<typeof listLinksQuerySchema>;
Loading
Loading