making strides in the device and link domain setup

This commit is contained in:
user
2026-03-27 23:58:06 +02:00
parent 8c45efc92e
commit c7c303a934
17 changed files with 1202 additions and 198 deletions

View File

@@ -0,0 +1,85 @@
import { errAsync, ResultAsync } from "neverthrow";
import { nanoid } from "nanoid";
import { db } from "@pkg/db";
import { type Err } from "@pkg/result";
import { FlowExecCtx } from "@core/flow.execution.context";
import { CreateLink, Link, LinkStatus, LinkWithDevice, UpdateLink } from "./data";
import { LinkRepository } from "./repository";
import { linkErrors } from "./errors";
export class LinkController {
constructor(private repo: LinkRepository) {}
list(fctx: FlowExecCtx): ResultAsync<Link[], Err> {
return this.repo.list(fctx);
}
getById(fctx: FlowExecCtx, id: number): ResultAsync<Link, Err> {
return this.repo.getById(fctx, id);
}
/**
* Fetch a link by its URL token, including the joined device.
* Used by apps/front to validate and resolve an incoming link.
*/
getByToken(fctx: FlowExecCtx, token: string): ResultAsync<LinkWithDevice, Err> {
return this.repo.getByToken(fctx, token);
}
/**
* Validate a token: must exist, be active, and not be expired.
* Returns the resolved link+device on success.
*/
validate(fctx: FlowExecCtx, token: string): ResultAsync<LinkWithDevice, Err> {
return this.repo.getByToken(fctx, token).andThen((l) => {
if (l.status !== LinkStatus.ACTIVE) {
return errAsync(linkErrors.linkNotActive(fctx, token));
}
if (l.expiresAt && l.expiresAt < new Date()) {
return errAsync(linkErrors.linkExpired(fctx, token));
}
return this.repo.touch(fctx, token).map(() => l);
});
}
/**
* Generate a new link. Token is auto-generated as a URL-safe nanoid.
*/
create(
fctx: FlowExecCtx,
data: Omit<CreateLink, "token">,
): ResultAsync<Link, Err> {
return this.repo.create(fctx, {
...data,
token: nanoid(12),
});
}
update(
fctx: FlowExecCtx,
id: number,
data: UpdateLink,
): ResultAsync<Link, Err> {
return this.repo.update(fctx, id, data);
}
assignDevice(
fctx: FlowExecCtx,
id: number,
deviceId: number | null,
): ResultAsync<Link, Err> {
return this.repo.update(fctx, id, { linkedDeviceId: deviceId });
}
revoke(fctx: FlowExecCtx, id: number): ResultAsync<Link, Err> {
return this.repo.update(fctx, id, { status: LinkStatus.REVOKED });
}
delete(fctx: FlowExecCtx, id: number): ResultAsync<boolean, Err> {
return this.repo.delete(fctx, id);
}
}
export function getLinkController(): LinkController {
return new LinkController(new LinkRepository(db));
}