import axios from 'axios'; import { sha1 } from '../utils'; type B2AuthResponse = { absoluteMinimumPartSize: number; accountId: string; allowed: { bucketId: string; bucketName: string; capabilities: string[]; namePrefix: string }; apiUrl: string; authorizationToken: string; downloadUrl: string; recommendedPartSize: number; }; type B2GetUploadUrlData = { uploadUrl: string; authorizationToken: string; }; type B2ListBucketsResponse = { buckets: { accountId: string; bucketId: string | null; bucketInfo: any; backetName: string | null; bucketType: string; corsRules: []; lifecycleRules: []; revision: number; }[]; }; export class B2Coffin { apiUrl: string; authToken: string; uploadToken: string; bucketId: string; uploadUrl: string; accountId: string; async auth(config: { applicationKeyId: string; applicationKey: string }) { const { applicationKeyId: keyId, applicationKey } = config; const key = `${keyId}:${applicationKey}`; const headers = { Authorization: `Basic ${Buffer.from(key).toString('base64')}` }; const { data } = await axios.get('https://api.backblazeb2.com/b2api/v2/b2_authorize_account', { headers }); this.apiUrl = data.apiUrl; this.authToken = data.authorizationToken; this.bucketId = data.allowed.bucketId; this.accountId = data.accountId; } async listBuckets() { const headers = { Authorization: this.authToken }; const { data } = await axios.get(`${this.apiUrl}/b2api/v2/b2_list_buckets`, { headers, params: { accountId: this.accountId, bucketId: this.bucketId } }); console.log(data); } async getUploadUrl() { const headers = { Authorization: this.authToken }; const { data } = await axios.get(`${this.apiUrl}/b2api/v2/b2_get_upload_url`, { headers, params: { bucketId: this.bucketId } }); this.uploadUrl = data.uploadUrl; this.uploadToken = data.authorizationToken; } async upload() { const fileName = 'test'; const contentType = 'text/plain'; const fileData = 'asdf'; const headers = { Authorization: this.uploadToken, 'X-Bz-File-Name': fileName, 'Content-Type': contentType, 'X-Bz-Content-Sha1': sha1(fileData) }; const { data } = await axios.post(this.uploadUrl, fileData, { headers }); console.log(data); } }