This commit is contained in:
2025-12-04 20:05:56 +08:00
parent 47fe4c1343
commit 57660d2d9c
13 changed files with 16138 additions and 0 deletions

56
src/cnb-core.ts Normal file
View File

@@ -0,0 +1,56 @@
export type CNBCoreOptions<T = {}> = {
token: string;
} & T;
export class CNBCore {
baseURL = 'https://api.cnb.cool';
token: string;
constructor(options: CNBCoreOptions) {
this.token = options.token;
}
async request({ url, method = 'GET', data, params }: { url: string, method?: string, data?: Record<string, any>, params?: Record<string, any> }): Promise<any> {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'Accept': 'application/json, application/vnd.cnb.api+json, application/vnd.cnb.web+json',
'Authorization': `Bearer ${this.token}`,
};
if (params) {
const queryString = new URLSearchParams(params).toString();
url += `?${queryString}`;
}
const response = await fetch(url, {
method,
headers,
body: data ? JSON.stringify(data) : undefined,
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Request failed with status ${response.status}: ${errorText}`);
}
const contentType = response.headers.get('Content-Type');
if (contentType && contentType.includes('application/json')) {
return response.json();
} else {
return response.text();
}
}
get<T = any>({ url, params }: { url: string, params?: Record<string, any> }): Promise<T> {
const fullUrl = new URL(url, this.baseURL).toString();
return this.request({ url: fullUrl, method: 'GET', params });
}
post<T = any>({ url, data }: { url: string, data?: Record<string, any> }): Promise<T> {
const fullUrl = new URL(url, this.baseURL).toString();
return this.request({ url: fullUrl, method: 'POST', data });
}
put<T = any>({ url, data }: { url: string, data?: Record<string, any> }): Promise<T> {
const fullUrl = new URL(url, this.baseURL).toString();
return this.request({ url: fullUrl, method: 'PUT', data });
}
delete<T = any>({ url, data }: { url: string, data?: Record<string, any> }): Promise<T> {
const fullUrl = new URL(url, this.baseURL).toString();
return this.request({ url: fullUrl, method: 'DELETE', data });
}
}