Skip to content

Commit

Permalink
support fetch and axios
Browse files Browse the repository at this point in the history
  • Loading branch information
foomoon committed Jan 7, 2024
1 parent c3e108b commit f03a289
Show file tree
Hide file tree
Showing 6 changed files with 456 additions and 188 deletions.
22 changes: 22 additions & 0 deletions dist/lib/fetchwrapper.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export default class FetchWrapper {
private baseURL;
private timeout;
defaults: FetchDefaults;
constructor(baseURL?: string, timeout?: number);
addHeaders(newHeaders: Record<string, string>): void;
request(endpoint: string, options?: RequestInit): Promise<FetchResponse>;
get(endpoint: string, options?: RequestInit): Promise<Response>;
post(endpoint: string, body: any, options?: RequestInit): Promise<FetchResponse>;
delete(endpoint: string, data: any): Promise<Response>;
put(endpoint: string, body: any, options?: RequestInit): Promise<FetchResponse>;
private stringifyBodyIfJson;
private createTimeoutPromise;
private setHeaderIfJson;
private handleResponseError;
}
export interface FetchDefaults {
headers: Record<string, string>;
}
export interface FetchResponse extends Response {
data?: any;
}
90 changes: 90 additions & 0 deletions dist/lib/fetchwrapper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
export default class FetchWrapper {
constructor(baseURL = "", timeout = 5000) {
this.defaults = {
headers: {},
};
this.baseURL = baseURL;
this.timeout = timeout;
}
addHeaders(newHeaders) {
this.defaults.headers = Object.assign(Object.assign({}, this.defaults.headers), newHeaders);
}
request(endpoint, options = {}) {
return __awaiter(this, void 0, void 0, function* () {
this.stringifyBodyIfJson(options);
const url = `${this.baseURL}${endpoint}`;
options.headers = Object.assign(Object.assign({}, this.defaults.headers), options.headers);
try {
const response = yield Promise.race([
fetch(url, options),
this.createTimeoutPromise(),
]);
const data = yield response.json();
this.handleResponseError(response, data);
const combinedFetchResponse = Object.assign(Object.assign({}, response), { data });
return combinedFetchResponse;
}
catch (error) {
throw error;
}
});
}
get(endpoint, options = {}) {
return __awaiter(this, void 0, void 0, function* () {
return this.request(endpoint, Object.assign(Object.assign({}, options), { method: "GET" }));
});
}
post(endpoint, body, options = {}) {
return __awaiter(this, void 0, void 0, function* () {
this.setHeaderIfJson(options);
return this.request(endpoint, Object.assign(Object.assign({}, options), { method: "POST", body }));
});
}
delete(endpoint, data) {
return __awaiter(this, void 0, void 0, function* () {
return this.request(endpoint, {
method: "DELETE",
body: JSON.stringify(data),
});
});
}
put(endpoint, body, options = {}) {
return __awaiter(this, void 0, void 0, function* () {
this.setHeaderIfJson(options);
return this.request(endpoint, Object.assign(Object.assign({}, options), { method: "PUT", body: JSON.stringify(body) }));
});
}
stringifyBodyIfJson(options) {
if (!options.headers) {
return;
}
if (options.headers["Content-Type"] === "application/json") {
options.body = JSON.stringify(options.body);
}
}
createTimeoutPromise() {
return new Promise((_, reject) => setTimeout(() => reject(new Error(`Request was aborted due to a timeout < ${this.timeout}ms. Increase the timeout to avoid this error.`)), this.timeout));
}
setHeaderIfJson(options) {
if (!options.headers) {
options.headers = {};
}
if (!options.headers["Content-Type"]) {
options.headers["Content-Type"] = "application/json";
}
}
handleResponseError(response, data) {
if (!response.ok) {
throw new Error(data.message || "Error fetching data");
}
}
}
55 changes: 30 additions & 25 deletions dist/lib/light.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/// <reference types="node" />
import { AxiosInstance, AxiosResponse } from "axios";
import FetchWrapper, { FetchResponse } from "./fetchwrapper.js";
import { Frame } from "./frame.js";
import { Movie } from "./movie.js";
import { rgbColor, hsvColor, deviceMode, timer, coordinate, layout } from "./interfaces.js";
Expand All @@ -11,7 +12,7 @@ import { rgbColor, hsvColor, deviceMode, timer, coordinate, layout } from "./int
export declare class Light {
ipaddr: string;
challenge: string;
net: AxiosInstance;
net: AxiosInstance | FetchWrapper;
token: AuthenticationToken | undefined;
activeLoginCall: boolean;
nleds: number | undefined;
Expand All @@ -22,8 +23,28 @@ export declare class Light {
* @constructor
* @param {string} ipaddr IP Address of the Twinkly device
*/
constructor(ipaddr: string, timeout?: number);
autoEndLoginCall(): Promise<void>;
constructor(ipaddr: string, timeout?: number, useFetch?: boolean);
/**
* Sends a POST request to the device, appending the required tokens
*
* @param {string} url
* @param {object} params
*/
sendPostRequest(url: string, data?: any, contentType?: string): Promise<any>;
/**
* Sends a DELETE request to the device, appending the required tokens
*
* @param {string} url
* @param {object} data
*/
sendDeleteRequest(url: string, data: any): Promise<any>;
/**
* Sends a GET request to the device, appending the required tokens
*
* @param {string} url
* @param {object} params
*/
sendGetRequest(url: string, params?: object, requiresToken?: boolean): Promise<any>;
/**
* Sends a login request
*
Expand All @@ -34,6 +55,10 @@ export declare class Light {
* Sends a logout request
*/
logout(): Promise<void>;
/**
* Automatically ends a login call after 1 second
*/
autoEndLoginCall(): Promise<void>;
/**
* Check that we are logged in to the device
*/
Expand Down Expand Up @@ -146,26 +171,6 @@ export declare class Light {
* @param {deviceMode} mode
*/
setMode(mode: deviceMode): Promise<void>;
/**
* Sends a POST request to the device, appending the required tokens
*
* @param {string} url
* @param {object} params
*/
sendPostRequest(url: string, data: any, contentType?: string): Promise<any>;
/**
*
* @param {string} url
* @param {object} data
*/
sendDeleteRequest(url: string, data: any): Promise<any>;
/**
* Sends a GET request to the device, appending the required tokens
*
* @param {string} url
* @param {object} params
*/
sendGetRequest(url: string, params?: object, requiresToken?: boolean): Promise<any>;
/**
* Send a movie config to the device
*
Expand Down Expand Up @@ -312,9 +317,9 @@ export declare class AuthenticationToken {
* Creates an instance of AuthenticationToken.
*
* @constructor
* @param {AxiosResponse} res Response from POST request
* @param {AxiosResponse | FetchResponse} res Response from POST request
*/
constructor(res: AxiosResponse);
constructor(res: AxiosResponse | FetchResponse);
/**
*
* @returns Token as string
Expand Down
Loading

0 comments on commit f03a289

Please sign in to comment.