61 lines
2.2 KiB
TypeScript
61 lines
2.2 KiB
TypeScript
import type { MessagesDataSource, MessagesSnapshot, SendMessageInput } from './messages-module.js';
|
|
|
|
interface Options {
|
|
readonly fetcher?: typeof fetch;
|
|
}
|
|
|
|
function record(value: unknown): Record<string, unknown> | undefined {
|
|
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
? (value as Record<string, unknown>)
|
|
: undefined;
|
|
}
|
|
|
|
export function createMessagesApiDataSource(options: Options = {}): MessagesDataSource {
|
|
const fetcher = options.fetcher ?? fetch;
|
|
return {
|
|
async load(instanceId, signal): Promise<MessagesSnapshot> {
|
|
const response = await fetcher(
|
|
`/api/v1/instances/${encodeURIComponent(instanceId)}/messages?limit=50&offset=0`,
|
|
{ headers: { accept: 'application/json' }, credentials: 'same-origin', signal },
|
|
);
|
|
if (!response.ok) throw new Error('message load failed');
|
|
const root = record(await response.json());
|
|
if (!Array.isArray(root?.messages)) throw new Error('message load failed');
|
|
return {
|
|
messages: root.messages.flatMap((item) => {
|
|
const value = record(item);
|
|
return typeof value?.id === 'string' &&
|
|
typeof value.phoneNumber === 'string' &&
|
|
typeof value.content === 'string' &&
|
|
typeof value.timestamp === 'string' &&
|
|
typeof value.status === 'string' &&
|
|
typeof value.direction === 'string'
|
|
? [
|
|
{
|
|
id: value.id,
|
|
phoneNumber: value.phoneNumber,
|
|
content: value.content,
|
|
timestamp: value.timestamp,
|
|
status: value.status,
|
|
direction: value.direction,
|
|
},
|
|
]
|
|
: [];
|
|
}),
|
|
};
|
|
},
|
|
async send(instanceId: string, input: SendMessageInput): Promise<void> {
|
|
const response = await fetcher(
|
|
`/api/v1/instances/${encodeURIComponent(instanceId)}/messages/send`,
|
|
{
|
|
method: 'POST',
|
|
headers: { accept: 'application/json', 'content-type': 'application/json' },
|
|
credentials: 'same-origin',
|
|
body: JSON.stringify(input),
|
|
},
|
|
);
|
|
if (!response.ok) throw new Error('message send failed');
|
|
},
|
|
};
|
|
}
|