Skip to content

Commit 96e70f5

Browse files
committed
plugin: refactor API internals
To add broader support for query params in the do() method
1 parent 7d1143a commit 96e70f5

File tree

1 file changed

+23
-13
lines changed

1 file changed

+23
-13
lines changed

plugin/src/api/index.ts

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,12 @@ export class TodoistApiClient {
3636
content,
3737
...(options ?? {}),
3838
});
39-
const response = await this.do("/tasks", "POST", body);
39+
const response = await this.do("/tasks", "POST", { json: body });
4040
return camelize(JSON.parse(response.body)) as Task;
4141
}
4242

4343
public async closeTask(id: TaskId): Promise<void> {
44-
await this.do(`/tasks/${id}/close`, "POST");
44+
await this.do(`/tasks/${id}/close`, "POST", {});
4545
}
4646

4747
public async getProjects(): Promise<Project[]> {
@@ -57,7 +57,7 @@ export class TodoistApiClient {
5757
}
5858

5959
public async getUser(): Promise<UserInfo> {
60-
const response = await this.do("/user", "GET");
60+
const response = await this.do("/user", "GET", {});
6161
return camelize(JSON.parse(response.body)) as UserInfo;
6262
}
6363

@@ -66,15 +66,15 @@ export class TodoistApiClient {
6666
let cursor: string | null = null;
6767

6868
do {
69-
const queryParams = new URLSearchParams(params);
69+
const queryParams: Record<string, string> = {
70+
...(params ?? {}),
71+
};
72+
7073
if (cursor) {
71-
queryParams.set("cursor", cursor);
74+
queryParams.cursor = cursor;
7275
}
7376

74-
const queryString = queryParams.toString();
75-
const fullPath = queryString ? `${path}?${queryString}` : path;
76-
77-
const response = await this.do(fullPath, "GET");
77+
const response = await this.do(path, "GET", { queryParams });
7878
const paginatedResponse = camelize(JSON.parse(response.body)) as PaginatedResponse<T>;
7979

8080
allResults.push(...paginatedResponse.results);
@@ -84,17 +84,27 @@ export class TodoistApiClient {
8484
return allResults;
8585
}
8686

87-
private async do(path: string, method: string, json?: object): Promise<WebResponse> {
87+
private async do(
88+
path: string,
89+
method: string,
90+
opts: { json?: object; queryParams?: Record<string, string> },
91+
): Promise<WebResponse> {
92+
let queryString = "";
93+
if (opts.queryParams) {
94+
const urlParams = new URLSearchParams(opts.queryParams);
95+
queryString = `?${urlParams.toString()}`;
96+
}
97+
8898
const params: RequestParams = {
89-
url: `https://api.todoist.com/api/v1${path}`,
99+
url: `https://api.todoist.com/api/v1${path}${queryString}`,
90100
method,
91101
headers: {
92102
Authorization: `Bearer ${this.token}`,
93103
},
94104
};
95105

96-
if (json !== undefined) {
97-
params.body = JSON.stringify(json);
106+
if (opts.json !== undefined) {
107+
params.body = JSON.stringify(opts.json);
98108
params.headers["Content-Type"] = "application/json";
99109
}
100110

0 commit comments

Comments
 (0)