Skip to content

Commit

Permalink
Add support for authorization headers, closes #27
Browse files Browse the repository at this point in the history
  • Loading branch information
davidmezzetti committed Dec 27, 2023
1 parent b29369a commit 397d779
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 8 deletions.
2 changes: 1 addition & 1 deletion examples/node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "txtai-node",
"dependencies": {
"sprintf-js": ">=1.1.2",
"txtai": ">=6.2.0"
"txtai": ">=6.3.0"
},
"devDependencies": {
"@babel/cli": ">=7.10.5",
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "txtai",
"version": "6.2.0",
"version": "6.3.0",
"author": "NeuML",
"description": "JavaScript client for txtai",
"license": "Apache-2.0",
Expand Down
34 changes: 28 additions & 6 deletions src/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,15 @@ class API {
/**
* Creates an API instance.
*
* @param url base url
* @param url api url
* @param token api token
*/
constructor(url) {
// Base url
this.url = url;
constructor(url, token) {
// API url
this.url = url ? url : process.env.TXTAI_API_URL

// API token
this.token = token ? token : process.env.TXTAI_API_TOKEN
}

/**
Expand All @@ -31,7 +35,7 @@ class API {
}

// Execute remote call
let res = await fetch(url);
let res = await fetch(url, {headers: this.headers()});

// Validate response and return JSON
return res.ok ? await res.json() : Promise.reject(`${res.status} ${res.statusText}`);
Expand All @@ -48,14 +52,32 @@ class API {
// Build URL
let url = `${this.url}/${method}`;

// Default headers
let defaults = {"Content-Type": "application/json"};

// Execute remote call
let res = await fetch(url, {method: "post",
body: JSON.stringify(params),
headers: {"content-type": "application/json"}});
headers: this.headers(defaults)});

// Validate response and return JSON
return res.ok ? await res.json() : Promise.reject(`${res.status} ${res.statusText}`);
}

/**
* Creates default HTTP headers.
*
* @param base base headers
* @return headers
*/
headers(base) {
let headers = base ? base : {};
if (this.token) {
headers["Authorization"] = "Bearer " + this.token;
}

return headers
}
}

export default API;

0 comments on commit 397d779

Please sign in to comment.