Skip to content

Commit

Permalink
feat: Make authToken optional for folksonomy client (#571)
Browse files Browse the repository at this point in the history
* feat: Make authToken optional for folksonomy client

* fix: Move auth token check into private method

* fix: Update naming

---------

Co-authored-by: Griffin Ciluffo <griffinciluffo@griffins-mbp.speedport.ip>
Co-authored-by: Griffin Ciluffo <griffinciluffo@Griffins-MacBook-Pro.local>
  • Loading branch information
3 people authored Dec 29, 2024
1 parent ec80bff commit 5679099
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion src/folksonomy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@ export type FolksonomyKey = {
export class Folksonomy {
private readonly fetch: typeof global.fetch;
private readonly baseUrl: string;
private authToken?: string;
readonly raw: ReturnType<typeof createClient<paths>>;

constructor(fetch: typeof global.fetch, authToken: string) {
constructor(fetch: typeof global.fetch, authToken?: string) {
this.baseUrl = "https://api.folksonomy.openfoodfacts.org";
this.authToken = authToken;

this.fetch = fetch;
this.raw = createClient({
Expand All @@ -32,6 +34,14 @@ export class Folksonomy {
});
}

private validateAuthToken(message?: string) {
if (!this.authToken) {
throw new Error(
message || "Auth token is required to perform this action",
);
}
}

/**
* Get the list of keys with statistics
*
Expand All @@ -53,6 +63,8 @@ export class Folksonomy {
}

async putTag(tag: FolksonomyTag): Promise<boolean> {
this.validateAuthToken();

const res = await this.raw.PUT("/product", { body: tag });

return res.response.status === 200;
Expand Down Expand Up @@ -81,6 +93,8 @@ export class Folksonomy {
* @returns if the tag was added or updated
*/
async addTag(tag: FolksonomyTag): Promise<boolean> {
this.validateAuthToken();

const res = await this.raw.POST("/product", {
body: tag,
});
Expand All @@ -94,6 +108,8 @@ export class Folksonomy {
* @returns if the tag was deleted
*/
async removeTag(tag: FolksonomyTag & { version: number }) {
this.validateAuthToken();

const res = await this.raw.DELETE("/product/{product}/{k}", {
params: {
path: { product: tag.product, k: tag.k },
Expand Down

0 comments on commit 5679099

Please sign in to comment.