Archived
邮件路由 15 条:账号 CRUD / 探测 / 立即拉取 / 试发 / 入站出站 / 附件原件 / 重新投递;领域错误翻状态码,厂商失败在 body 里说
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TM4kUBvekALu9qqmp7D3wr
This commit is contained in:
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
* 邮件收发路由(设计稿 §7.2;ADR-013)。归属在契约的 access 上,中间件统一判;
|
||||
* 这里只做 zod 校验、调用用例、把领域错误翻成状态码。
|
||||
* 探测 / 试发 / 拉取的**厂商失败在 200 的 body 里如实说** —— 不是接口错误。
|
||||
*/
|
||||
import type { Context, Hono } from 'hono';
|
||||
import type { ApiError } from '@contracts';
|
||||
import {
|
||||
createMailAccountRoute,
|
||||
deleteMailAccountRoute,
|
||||
getMailAccountRoute,
|
||||
getMailInboundRoute,
|
||||
listMailAccountsRoute,
|
||||
listMailInboundRoute,
|
||||
listMailOutboundRoute,
|
||||
mailAttachmentRoute,
|
||||
mailRawRoute,
|
||||
pollMailAccountRoute,
|
||||
probeMailAccountRoute,
|
||||
probeMailDraftRoute,
|
||||
redeliverMailInboundRoute,
|
||||
sendTestMailRoute,
|
||||
updateMailAccountRoute,
|
||||
} from '@contracts';
|
||||
import type { MailService } from '@modules/mail';
|
||||
import {
|
||||
MailAccountDisabledError,
|
||||
MailAccountNameTakenError,
|
||||
MailAccountNotFoundError,
|
||||
MailAttachmentNotFoundError,
|
||||
MailInboundNotFoundError,
|
||||
MailNoDefaultAccountError,
|
||||
MailPollBusyError,
|
||||
MailSecretMissingError,
|
||||
MailSendInvalidError,
|
||||
MailSubscriberUnknownError,
|
||||
} from '@modules/mail';
|
||||
import type { AppEnv } from '../http-env.ts';
|
||||
import { staffOf } from '../http-env.ts';
|
||||
|
||||
export type MailRouteDeps = { readonly mail: MailService };
|
||||
|
||||
/** 领域错误 → 状态码;认不出的交回 onError(500) */
|
||||
export function mailErrorResponse(error: unknown): { status: 400 | 404 | 409 | 412; body: ApiError } | undefined {
|
||||
if (
|
||||
error instanceof MailAccountNotFoundError ||
|
||||
error instanceof MailInboundNotFoundError ||
|
||||
error instanceof MailAttachmentNotFoundError ||
|
||||
error instanceof MailSubscriberUnknownError
|
||||
) {
|
||||
return { status: 404, body: { code: 'not-found', message: error.message } };
|
||||
}
|
||||
if (error instanceof MailAccountNameTakenError || error instanceof MailPollBusyError) {
|
||||
return { status: 409, body: { code: 'conflict', message: error.message } };
|
||||
}
|
||||
if (error instanceof MailAccountDisabledError || error instanceof MailNoDefaultAccountError || error instanceof MailSecretMissingError) {
|
||||
return { status: 412, body: { code: 'precondition-failed', message: error.message } };
|
||||
}
|
||||
if (error instanceof MailSendInvalidError) {
|
||||
return { status: 400, body: { code: 'validation-failed', message: error.message, detail: error.problems } };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function invalid(c: Context<AppEnv>, message: string, detail: unknown): Response {
|
||||
const body: ApiError = { code: 'validation-failed', message, detail };
|
||||
return c.json(body, 400);
|
||||
}
|
||||
|
||||
async function jsonBody(c: Context<AppEnv>): Promise<unknown> {
|
||||
const text = await c.req.text();
|
||||
if (text.trim() === '') return {};
|
||||
try {
|
||||
return JSON.parse(text) as unknown;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function registerMailRoutes(app: Hono<AppEnv>, deps: MailRouteDeps): void {
|
||||
const { mail } = deps;
|
||||
|
||||
const guarded = async (c: Context<AppEnv>, run: () => Promise<Response>): Promise<Response> => {
|
||||
try {
|
||||
return await run();
|
||||
} catch (error) {
|
||||
const mapped = mailErrorResponse(error);
|
||||
if (mapped === undefined) throw error;
|
||||
return c.json(mapped.body, mapped.status);
|
||||
}
|
||||
};
|
||||
|
||||
/* ── 账号 ── */
|
||||
|
||||
app.get(listMailAccountsRoute.path, async (c) => c.json({ accounts: await mail.listAccounts() }));
|
||||
|
||||
app.post(createMailAccountRoute.path, async (c) => {
|
||||
const parsed = createMailAccountRoute.body.safeParse(await jsonBody(c));
|
||||
if (!parsed.success) return invalid(c, '账号入参不合法', parsed.error.issues);
|
||||
return guarded(c, async () => c.json(await mail.createAccount(parsed.data)));
|
||||
});
|
||||
|
||||
app.post(probeMailDraftRoute.path, async (c) => {
|
||||
const parsed = probeMailDraftRoute.body.safeParse(await jsonBody(c));
|
||||
if (!parsed.success) return invalid(c, '账号入参不合法', parsed.error.issues);
|
||||
const accountId = c.req.query('accountId');
|
||||
return guarded(c, async () =>
|
||||
c.json(await mail.probe({ input: parsed.data, ...(accountId === undefined || accountId === '' ? {} : { accountId }) })),
|
||||
);
|
||||
});
|
||||
|
||||
app.get(getMailAccountRoute.path, async (c) => guarded(c, async () => c.json(await mail.getAccount(c.req.param('accountId')))));
|
||||
|
||||
app.put(updateMailAccountRoute.path, async (c) => {
|
||||
const parsed = updateMailAccountRoute.body.safeParse(await jsonBody(c));
|
||||
if (!parsed.success) return invalid(c, '账号入参不合法', parsed.error.issues);
|
||||
return guarded(c, async () => c.json(await mail.updateAccount(c.req.param('accountId'), parsed.data)));
|
||||
});
|
||||
|
||||
app.delete(deleteMailAccountRoute.path, async (c) =>
|
||||
guarded(c, async () => {
|
||||
await mail.deleteAccount(c.req.param('accountId'));
|
||||
return c.json({ ok: true as const });
|
||||
}),
|
||||
);
|
||||
|
||||
app.post(probeMailAccountRoute.path, async (c) => guarded(c, async () => c.json(await mail.probe({ accountId: c.req.param('accountId') }))));
|
||||
|
||||
app.post(pollMailAccountRoute.path, async (c) => guarded(c, async () => c.json(await mail.pollNow(c.req.param('accountId')))));
|
||||
|
||||
app.post(sendTestMailRoute.path, async (c) => {
|
||||
const parsed = sendTestMailRoute.body.safeParse(await jsonBody(c));
|
||||
if (!parsed.success) return invalid(c, '试发入参不合法', parsed.error.issues);
|
||||
const me = staffOf(c);
|
||||
return guarded(c, async () =>
|
||||
c.json(
|
||||
await mail.send({
|
||||
accountId: c.req.param('accountId'),
|
||||
to: [parsed.data.to],
|
||||
cc: [],
|
||||
bcc: [],
|
||||
subject: parsed.data.subject,
|
||||
text: parsed.data.text,
|
||||
references: [],
|
||||
attachments: [],
|
||||
requestedBy: { kind: 'ops', ...(me === undefined ? {} : { staffId: me.id }) },
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
/* ── 入站 ── */
|
||||
|
||||
app.get(listMailInboundRoute.path, async (c) => {
|
||||
const query = listMailInboundRoute.query.safeParse(c.req.query());
|
||||
if (!query.success) return invalid(c, '查询参数不合法', query.error.issues);
|
||||
return c.json({ mails: await mail.listInbound({ accountId: query.data.accountId, limit: query.data.limit }) });
|
||||
});
|
||||
|
||||
app.get(getMailInboundRoute.path, async (c) => guarded(c, async () => c.json(await mail.getInbound(c.req.param('mailId')))));
|
||||
|
||||
app.get(mailAttachmentRoute.path, async (c) => {
|
||||
const params = mailAttachmentRoute.params.safeParse({ mailId: c.req.param('mailId'), index: c.req.param('index') });
|
||||
if (!params.success) return invalid(c, '附件序号不合法', params.error.issues);
|
||||
return guarded(c, async () => {
|
||||
const file = await mail.attachment(params.data.mailId, params.data.index);
|
||||
return c.json({ name: file.name, contentType: file.contentType, dataBase64: Buffer.from(file.bytes).toString('base64') });
|
||||
});
|
||||
});
|
||||
|
||||
app.get(mailRawRoute.path, async (c) =>
|
||||
guarded(c, async () => {
|
||||
const file = await mail.raw(c.req.param('mailId'));
|
||||
return c.json({ name: file.name, contentType: 'message/rfc822' as const, dataBase64: Buffer.from(file.bytes).toString('base64') });
|
||||
}),
|
||||
);
|
||||
|
||||
app.post(redeliverMailInboundRoute.path, async (c) => {
|
||||
const parsed = redeliverMailInboundRoute.body.safeParse(await jsonBody(c));
|
||||
if (!parsed.success) return invalid(c, '入参不合法', parsed.error.issues);
|
||||
return guarded(c, async () => c.json({ deliveries: await mail.redeliver(c.req.param('mailId'), parsed.data.subscriber) }));
|
||||
});
|
||||
|
||||
/* ── 出站 ── */
|
||||
|
||||
app.get(listMailOutboundRoute.path, async (c) => {
|
||||
const query = listMailOutboundRoute.query.safeParse(c.req.query());
|
||||
if (!query.success) return invalid(c, '查询参数不合法', query.error.issues);
|
||||
return c.json({ mails: await mail.listOutbound({ accountId: query.data.accountId, limit: query.data.limit }) });
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user