Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Make authToken optional for folksonomy client #571

Merged
merged 4 commits into from
Dec 29, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading