diff --git a/src/folksonomy.ts b/src/folksonomy.ts index 005007d..74e9c34 100644 --- a/src/folksonomy.ts +++ b/src/folksonomy.ts @@ -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>; - 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({ @@ -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 * @@ -53,6 +63,8 @@ export class Folksonomy { } async putTag(tag: FolksonomyTag): Promise { + this.validateAuthToken(); + const res = await this.raw.PUT("/product", { body: tag }); return res.response.status === 200; @@ -81,6 +93,8 @@ export class Folksonomy { * @returns if the tag was added or updated */ async addTag(tag: FolksonomyTag): Promise { + this.validateAuthToken(); + const res = await this.raw.POST("/product", { body: tag, }); @@ -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 },