seaweedfs-client
Version:
Nodejs Seaweedfs Client
145 lines (125 loc) • 3.38 kB
text/typescript
import axios, { Method } from 'axios';
import FormData from 'form-data';
import { readFile } from 'fs';
import { sign } from 'jsonwebtoken';
import { join } from 'path';
export type FilterConstructorParams = {
baseUrl: string;
jwtSecretKey?: string;
baseRemoteFilePath?: string;
};
export class Filter {
private baseUrl: string;
private jwtSecretKey: string | undefined;
private baseRemoteFilePath: string;
constructor(params: FilterConstructorParams) {
this.baseUrl = params.baseUrl;
this.jwtSecretKey = params.jwtSecretKey;
this.baseRemoteFilePath = params.baseRemoteFilePath || '';
}
private genJwtToken(): string | undefined {
if (this.jwtSecretKey) {
return sign({}, this.jwtSecretKey, { expiresIn: '1h' });
}
}
private async prepareFileBody(file: string | Buffer): Promise<Buffer> {
return new Promise((resolve, reject) => {
if (file instanceof Buffer) {
return resolve(file);
}
readFile(file, {}, (err, data) => {
if (err) {
return reject(err);
}
resolve(data);
});
});
}
async _request(
method: Method,
urlPath: string,
options?: {
body?: Record<string, unknown> | FormData;
params?: Record<string, number | string> | URLSearchParams;
headers?: Record<string, string>;
}
) {
const targetPath = join(this.baseRemoteFilePath, urlPath);
const url = new URL(targetPath, this.baseUrl);
return axios({
method,
url: url.href,
data: options?.body,
params: options?.params,
headers: {
...options?.headers,
Authorization: this.jwtSecretKey ? `Bearer ${this.genJwtToken()}` : '',
},
maxContentLength: Infinity,
maxBodyLength: Infinity,
});
}
async uploadFile(
file: string | Buffer,
saveAs: string,
options?: {
params: Record<string, string | number>;
}
) {
const fileBody = await this.prepareFileBody(file);
const formData = new FormData();
formData.append('file', fileBody);
const savePath = join(this.baseRemoteFilePath, saveAs);
const url = new URL(savePath, this.baseUrl);
return this._request('post', saveAs, {
body: formData,
params: options?.params || {},
headers: {
...formData.getHeaders(),
},
})
.then(res => {
return {
url: url.href,
path: url.pathname,
...res.data,
};
})
.catch(error => {
throw error;
});
}
async createDir(dirPath: string) {
return this._request('post', dirPath);
}
private _delete(
targetPath: string,
options?: {
recursive?: boolean;
ignoreRecursiveError?: boolean;
skipChunkDeletion?: boolean;
}
) {
const params = new URLSearchParams();
if (options?.recursive) {
params.append('recursive', 'true');
}
if (options?.ignoreRecursiveError) {
params.append('ignoreRecursiveError', 'true');
}
if (options?.skipChunkDeletion) {
params.append('skipChunkDeletion', 'true');
}
return this._request('delete', targetPath, {
params,
});
}
async deleteFile(filePath: string) {
return this._delete(filePath);
}
async deleteDir(dirPath: string) {
return this._delete(dirPath, {
recursive: true,
});
}
}