Skip to content

Commit

Permalink
Revert "fix: update throttle"
Browse files Browse the repository at this point in the history
  • Loading branch information
johannes-lindgren authored Nov 22, 2024
1 parent 59be18a commit e96834b
Show file tree
Hide file tree
Showing 13 changed files with 171 additions and 254 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,4 @@ jobs:
- name: Install dependencies
run: pnpm install
- name: Run Lint
run: pnpm run lint
run: pnpm run lint
43 changes: 17 additions & 26 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,13 @@ import type {
ISbCustomFetch,
ISbLinkURLObject,
ISbNode,
ISbResponse,
ISbResponseData,
ISbResult,
ISbStories,
ISbStoriesParams,
ISbStory,
ISbStoryData,
ISbStoryParams,
ThrottleFn,
} from './interfaces';

let memory: Partial<IMemoryType> = {};
Expand All @@ -48,6 +47,15 @@ interface ISbFlatMapped {
data: any;
}

export interface ISbResponseData {
link_uuids: string[];
links: string[];
rel_uuids: string[];
rels: any;
story: ISbStoryData;
stories: Array<ISbStoryData>;
}

const _VERSION = {
V1: 'v1',
V2: 'v2',
Expand All @@ -60,7 +68,7 @@ class Storyblok {
private client: SbFetch;
private maxRetries: number;
private retriesDelay: number;
private throttle: ReturnType<typeof throttledQueue>;
private throttle: ThrottleFn;
private accessToken: string;
private cache: ISbCache;
private helpers: SbHelpers;
Expand Down Expand Up @@ -140,12 +148,7 @@ class Storyblok {

this.maxRetries = config.maxRetries || 10;
this.retriesDelay = 300;
this.throttle = throttledQueue(
this.throttledRequest.bind(this),
rateLimit,
1000,
);

this.throttle = throttledQueue(this.throttledRequest, rateLimit, 1000);
this.accessToken = config.accessToken || '';
this.relations = {} as RelationsType;
this.links = {} as LinksType;
Expand Down Expand Up @@ -278,9 +281,7 @@ class Storyblok {
): Promise<ISbResponseData> {
const url = `/${slug}`;

return Promise.resolve(
this.throttle('post', url, params, fetchOptions),
) as Promise<ISbResponseData>;
return Promise.resolve(this.throttle('post', url, params, fetchOptions));
}

public put(
Expand All @@ -290,9 +291,7 @@ class Storyblok {
): Promise<ISbResponseData> {
const url = `/${slug}`;

return Promise.resolve(
this.throttle('put', url, params, fetchOptions),
) as Promise<ISbResponseData>;
return Promise.resolve(this.throttle('put', url, params, fetchOptions));
}

public delete(
Expand All @@ -302,9 +301,7 @@ class Storyblok {
): Promise<ISbResponseData> {
const url = `/${slug}`;

return Promise.resolve(
this.throttle('delete', url, params, fetchOptions),
) as Promise<ISbResponseData>;
return Promise.resolve(this.throttle('delete', url, params, fetchOptions));
}

public getStories(
Expand Down Expand Up @@ -619,12 +616,7 @@ class Storyblok {

return new Promise(async (resolve, reject) => {
try {
const res = (await this.throttle(
'get',
url,
params,
fetchOptions,
)) as ISbResponse;
const res = await this.throttle('get', url, params, fetchOptions);
if (res.status !== 200) {
return reject(res);
}
Expand All @@ -643,8 +635,7 @@ class Storyblok {
}

if (response.data.story || response.data.stories) {
const resolveId = (this.resolveCounter
= ++this.resolveCounter % 1000);
const resolveId = (this.resolveCounter = ++this.resolveCounter % 1000);
await this.resolveStories(response.data, params, `${resolveId}`);
}

Expand Down
31 changes: 2 additions & 29 deletions src/interfaces.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { ResponseFn } from './sbFetch';
import type Method from './constants';

export interface ISbStoriesParams
extends Partial<ISbStoryData>,
Expand Down Expand Up @@ -242,7 +241,6 @@ export interface ISbResponse {
data: any;
status: number;
statusText: string;
headers: any;
}

export interface ISbError {
Expand Down Expand Up @@ -341,35 +339,10 @@ export interface ISbLinks {
};
}

export interface Queue<T> {
resolve: (value: unknown) => void;
reject: (reason?: unknown) => void;
args: T;
}

export interface ISbResponseData {
link_uuids: string[];
links: string[];
rel_uuids: string[];
rels: any;
story: ISbStoryData;
stories: Array<ISbStoryData>;
export interface ThrottleFn {
(...args: any): any;
}

export interface ISbThrottle<
T extends (...args: Parameters<T>) => ReturnType<T>,
> {
abort?: () => void;
(...args: Parameters<T>): Promise<unknown>;
}

export type ISbThrottledRequest = (
type: Method,
url: string,
params: ISbStoriesParams,
fetchOptions?: ISbCustomFetch
) => Promise<unknown>;

export type AsyncFn = (...args: any) => [] | Promise<ISbResult>;

export type ArrayFn = (...args: any) => void;
Expand Down
48 changes: 0 additions & 48 deletions src/throttlePromise.test.ts

This file was deleted.

75 changes: 41 additions & 34 deletions src/throttlePromise.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
import type { ISbThrottle, Queue } from './interfaces';
import type { ThrottleFn } from './interfaces';

class AbortError extends Error {
constructor(msg: string) {
super(msg);
this.name = 'AbortError';
}
interface Shifted {
args: any;
self: any;
resolve: (args: any) => any;
}

interface Queue {
resolve: (args: any) => any;
reject: (args: any) => any;
args: any[];
self: any;
}

function throttledQueue<T extends (...args: Parameters<T>) => ReturnType<T>>(
fn: T,
limit: number,
interval: number,
): ISbThrottle<T> {
interface ISbThrottle {
abort: () => any;
(args: []): Promise<Queue>;
name: string;
AbortError?: () => void;
}

function throttledQueue(fn: ThrottleFn, limit: number, interval: number) {
if (!Number.isFinite(limit)) {
throw new TypeError('Expected `limit` to be a finite number');
}
Expand All @@ -20,49 +29,45 @@ function throttledQueue<T extends (...args: Parameters<T>) => ReturnType<T>>(
throw new TypeError('Expected `interval` to be a finite number');
}

const queue: Queue<Parameters<T>>[] = [];
const queue: Queue[] = [];
let timeouts: ReturnType<typeof setTimeout>[] = [];
let activeCount = 0;
let isAborted = false;

const next = async () => {
const next = function () {
activeCount++;

const x = queue.shift();
if (x) {
const res = await fn(...x.args);
x.resolve(res);
}

const id = setTimeout(() => {
activeCount--;

if (queue.length > 0) {
next();
}

timeouts = timeouts.filter(currentId => currentId !== id);
timeouts = timeouts.filter((currentId) => {
return currentId !== id;
});
}, interval);

if (!timeouts.includes(id)) {
timeouts.push(id);
}

const x = queue.shift() as unknown as Shifted;
x.resolve(fn.apply(x.self, x.args));
};

const throttled: ISbThrottle<T> = (...args) => {
if (isAborted) {
return Promise.reject(
new Error(
'Throttled function is already aborted and not accepting new promises',
),
);
}
const throttled: ISbThrottle = function (
this: ISbThrottle,
...args: []
): Promise<Queue> {
const self = this;

return new Promise((resolve, reject) => {
queue.push({
resolve,
reject,
args,
self,
});

if (activeCount < limit) {
Expand All @@ -71,14 +76,16 @@ function throttledQueue<T extends (...args: Parameters<T>) => ReturnType<T>>(
});
};

throttled.abort = () => {
isAborted = true;
throttled.abort = function () {
timeouts.forEach(clearTimeout);
timeouts = [];

queue.forEach(x =>
x.reject(() => new AbortError('Throttle function aborted')),
);
queue.forEach((x) => {
x.reject(function (this: ISbThrottle) {
Error.call(this, 'Throttled function aborted');
this.name = 'AbortError';
});
});
queue.length = 0;
};

Expand Down
Loading

0 comments on commit e96834b

Please sign in to comment.