@kevisual/noco
Version:
一个轻量级的 NocoDB API SDK,支持表记录操作和 Base 管理功能。
100 lines (94 loc) • 2.46 kB
text/typescript
type HeadersInit = {
'xc-token': string;
[key: string]: string;
};
type FetchOptions = {
method?: string;
headers?: HeadersInit;
body?: string;
};
type MakeRequestOptions = {
params?: Record<string, any>;
data?: Record<string, any>;
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
json?: boolean;
// body 优先级别高于 data
isFromData?: boolean;
body?: any;
headers?: Record<string, string>;
};
export class Query {
baseURL: string;
token: string;
constructor({ baseURL, token }: { baseURL: string; token: string }) {
this.baseURL = baseURL;
this.token = token;
}
makeRequest(endpoint: string, options: MakeRequestOptions) {
const url = new URL(endpoint, this.baseURL);
const isJson = options.json ?? true;
const bodyIsFormData = options.isFromData || false;
if (options.params) {
Object.entries(options.params).forEach(([key, value]) => {
url.searchParams.append(key, String(value));
});
}
const method = options.method || 'GET';
const headers: HeadersInit = {
'xc-token': `${this.token}`,
...options.headers,
};
// 如果 body 不是 FormData,才设置 Content-Type
if (!bodyIsFormData) {
headers['Content-Type'] = 'application/json';
}
const fetchOptions: FetchOptions = {
method,
headers,
};
if (options.body) {
fetchOptions.body = options.body;
} else if (options.data) {
fetchOptions.body = JSON.stringify(options.data);
}
return fetch(url.href, fetchOptions).then(async (response) => {
if (!response.ok) {
return { code: response.status, message: response.statusText };
}
if (isJson) {
const result = await response.json();
const isArray = Array.isArray(result);
if (isArray) {
return {
code: 200,
data: { list: result },
};
} else if (result && typeof result === 'object' && !('code' in result)) {
return {
code: 200,
data: result,
}
}
return result;
}
return response;
});
}
}
export type ResponseList<T = any> = {
code: number;
data: {
list: T[];
pageInfo?: {
totalRows?: number;
page?: number;
pageSize?: number;
isFirstPage?: boolean;
isLastPage?: boolean;
};
}
};
export type Result<T = any> = {
code: number;
data: T;
};