@bit-ui-libs/common
Version:
This library was generated with [Nx](https://nx.dev).
76 lines (69 loc) • 2.67 kB
text/typescript
import { BaseService } from '../api/services/base-service';
import { UpdateAttachmentResponse, UploadedAttachmentData, createQueryParams } from '../common';
import { CreateAttachmentRequest, CreateAttachmentsPayload, UpdateAttachmentRequest } from './interfaces';
export interface GetAttachmentLinkOpts {
apiUrl: string;
id: string;
bitToken: string;
accessToken: string;
thumb?: boolean;
}
export function getAttachmentLink(opts: GetAttachmentLinkOpts) {
const params = {
thumb: opts.thumb ? 'true' : undefined,
bit_token: opts.bitToken,
access_token: opts.accessToken,
};
return `${opts.apiUrl}/core-events/v1/chain-assets/attachments/${opts.id}/view?${createQueryParams(params)}`;
}
interface CreateAndUploadAttachmentsOpts {
service: BaseService;
chainApiUrl: string;
req: CreateAttachmentsPayload;
}
export async function createAndUploadAttachments(
opts: CreateAndUploadAttachmentsOpts
): Promise<UploadedAttachmentData[]> {
const { service, chainApiUrl, req } = opts;
const { eventId, req: input, onUpload } = req;
// 1. Prepare array of attachments to initialize
const docs = input.docs
// Exclude attachments that are already initialized
// .filter((d) => !event.attachments.some((a) => a.classification === d.classification))
// Exclude image data first, as we're just initializing the attachments
.map((d) => ({ ...d, data: undefined }));
// Initialize attachments
const initializeInput = { ...input, docs };
const initializedAttachments = await service.post<UploadedAttachmentData[], CreateAttachmentRequest>(
`${chainApiUrl}/${eventId}/attachments`,
initializeInput
);
// 2. Update Attachments (upload / pass image data to the initialized attachments)
const updatedDocs: UploadedAttachmentData[] = [];
let i = 0;
for (const d of input.docs) {
onUpload?.(i + 1, input.docs.length);
const req: UpdateAttachmentRequest = {
application: input.application,
docs: [
{
mimeType: d.mimeType,
docType: d.docType,
classification: d.classification,
docId: initializedAttachments[i].docId,
name: d.name,
description: d.description,
data: d.data ?? '',
isMain: d.isMain,
},
],
};
await service.put<UpdateAttachmentResponse, UpdateAttachmentRequest>(`${chainApiUrl}/${eventId}/attachments`, req, {
onUploadProgress: (e) => console.log('Upload attachment progress:', e),
});
i++;
// TODO: Please fix typing, just a quick fix for build error
updatedDocs.push(req.docs[0] as UploadedAttachmentData);
}
return updatedDocs;
}