Files

159 lines
4.1 KiB
TypeScript

import { randomUUID } from 'node:crypto';
import { Pool } from 'pg';
import { expect } from 'vitest';
import type { Chat } from '../../src/chats/chat.js';
import type { ApiErrorBody } from '../../src/common/errors/api-error.js';
import type { Message } from '../../src/messages/message.js';
import type { Attachment } from '../../src/attachments/attachment.js';
import type { User } from '../../src/users/user.js';
export const baseUrl = (
process.env.API_BASE_URL ?? 'http://localhost:8080'
).replace(/\/+$/u, '');
export const password = 'integration:пароль🔐';
const runId = randomUUID().replaceAll('-', '').slice(0, 10);
let sequence = 0;
export type Actor = { user: User; token: string };
export type HttpResult<T> = { body: T; response: Response };
export function database(): Pool {
return new Pool({
connectionString: process.env.DATABASE_URL,
connectionTimeoutMillis: 5000,
});
}
export async function http<T = unknown>(
path: string,
init: RequestInit = {},
): Promise<HttpResult<T>> {
const response = await fetch(`${baseUrl}${path}`, init);
const text = await response.text();
let body: unknown = undefined;
if (text) {
try {
body = JSON.parse(text);
} catch {
body = text;
}
}
return { body: body as T, response };
}
export function json(
body: unknown,
headers: Record<string, string> = {},
): RequestInit {
return {
method: 'POST',
headers: { 'content-type': 'application/json', ...headers },
body: JSON.stringify(body),
};
}
export function bearer(token: string): Record<string, string> {
return { authorization: `Bearer ${token}` };
}
export function expectError(
result: HttpResult<ApiErrorBody>,
status: number,
code: string,
): void {
expect(result.response.status).toBe(status);
expect(result.body.error.code).toBe(code);
expect(result.body.error.request_id).toBe(
result.response.headers.get('x-request-id'),
);
}
export async function actor(): Promise<Actor> {
const username = `e2e_${runId}_${sequence++}`.slice(0, 32);
const created = await http<User>(
'/api/v1/users',
json({ username, display_name: 'Attachments e2e', password }),
);
expect(created.response.status).toBe(201);
const basic = Buffer.from(`${username}:${password}`, 'utf8').toString(
'base64',
);
const session = await http<{ token: string }>('/api/v1/auth/sessions', {
method: 'POST',
headers: { authorization: `Basic ${basic}` },
});
expect(session.response.status).toBe(201);
return { user: created.body, token: session.body.token };
}
export async function createChat(
owner: Actor,
members: Actor[],
): Promise<Chat> {
const result = await http<Chat>(
'/api/v1/chats',
json(
{
title: 'attachments',
member_ids: [owner.user.id, ...members.map((m) => m.user.id)],
},
bearer(owner.token),
),
);
expect(result.response.status).toBe(201);
return result.body;
}
/** `query` is sent verbatim so tests can craft malformed filename parameters. */
export function uploadRaw(
token: string,
chatId: string,
query: string,
body: Buffer | undefined,
contentType = 'image/png',
): Promise<HttpResult<Attachment & ApiErrorBody>> {
return http(`/api/v1/chats/${chatId}/attachments${query}`, {
method: 'POST',
headers: { ...bearer(token), 'content-type': contentType },
body: body as BodyInit | undefined,
});
}
export function upload(
token: string,
chatId: string,
body: Buffer | undefined,
options: { filename?: string; contentType?: string } = {},
) {
return uploadRaw(
token,
chatId,
`?filename=${encodeURIComponent(options.filename ?? 'picture.png')}`,
body,
options.contentType ?? 'image/png',
);
}
export async function download(
token: string,
attachmentId: string,
): Promise<{ response: Response; bytes: Buffer }> {
const response = await fetch(
`${baseUrl}/api/v1/attachments/${attachmentId}/content`,
{ headers: bearer(token) },
);
return { response, bytes: Buffer.from(await response.arrayBuffer()) };
}
export function postMessage(
token: string,
chatId: string,
body: unknown,
key = randomUUID().replaceAll('-', ''),
) {
return http<Message & ApiErrorBody>(
`/api/v1/chats/${chatId}/messages`,
json(body, { ...bearer(token), 'idempotency-key': key }),
);
}