@kevisual/noco
Version:
```ts const nocoAPi = new NocoApi({ baseURL: config.NOCODB_URL, token: config.NOCODB_API_KEY, });
57 lines (55 loc) • 1.49 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;
};
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;
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}`,
};
headers['Content-Type'] = 'application/json';
const fetchOptions: FetchOptions = {
method,
headers,
};
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();
result.code = 200;
return result;
}
return response;
});
}
}