@kevisual/noco
Version:
```ts const nocoAPi = new NocoApi({ baseURL: config.NOCODB_URL, token: config.NOCODB_API_KEY, });
117 lines (114 loc) • 2.83 kB
JavaScript
// src/api.ts
class Query {
baseURL;
token;
constructor({ baseURL, token }) {
this.baseURL = baseURL;
this.token = token;
}
makeRequest(endpoint, options) {
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 = {
"xc-token": `${this.token}`
};
headers["Content-Type"] = "application/json";
const 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;
});
}
}
// src/base.ts
class NocoApi {
query;
record;
constructor(options) {
const table = options.table;
const token = options.token;
const baseURL = options.baseURL;
this.query = new Query({ baseURL, token });
this.record = new Record(this.query, table);
}
}
class Record {
query;
table;
constructor(query, table) {
this.query = query;
this.table = table;
}
list(params = {}) {
return this.query.makeRequest(`/api/v2/tables/${this.table}/records`, {
method: "GET",
params
});
}
create(data) {
return this.query.makeRequest(`/api/v2/tables/${this.table}/records`, {
method: "POST",
data
});
}
read(id) {
return this.query.makeRequest(`/api/v2/tables/${this.table}/records/${id}`, {
method: "GET"
});
}
update(data) {
return this.query.makeRequest(`/api/v2/tables/${this.table}/records`, {
method: "PATCH",
data
});
}
delete(data) {
return this.query.makeRequest(`/api/v2/tables/${this.table}/records`, {
method: "DELETE",
data
});
}
count() {
return this.query.makeRequest(`/api/v2/tables/${this.table}/records/count`, {
method: "GET"
});
}
listLinks(linkFieldId, Id) {
return this.query.makeRequest(`/api/v2/tables/${this.table}/links/${linkFieldId}/records/${Id}`, {
method: "GET"
});
}
updateLinks(linkFieldId, Id, data) {
return this.query.makeRequest(`/api/v2/tables/${this.table}/links/${linkFieldId}/records/${Id}`, {
method: "POST",
data
});
}
deleteLinks(linkFieldId, Id) {
return this.query.makeRequest(`/api/v2/tables/${this.table}/links/${linkFieldId}/records/${Id}`, {
method: "DELETE"
});
}
}
export {
NocoApi
};