Skip to content

Commit

Permalink
refactor: eslint more strict and some minor refactors
Browse files Browse the repository at this point in the history
  • Loading branch information
arthurfiorette committed Sep 11, 2021
1 parent 4825739 commit d2c2a56
Show file tree
Hide file tree
Showing 10 changed files with 36 additions and 52 deletions.
4 changes: 2 additions & 2 deletions src/axios/cache.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { AxiosInstance } from 'axios';
import { defaultHeaderInterpreter } from '../header';
import { applyRequestInterceptor } from '../interceptors/request';
import { applyResponseInterceptor } from '../interceptors/response';
import { MemoryStorage } from '../storage/memory';
import { defaultHeaderInterpreter } from '../header';
import { defaultKeyGenerator } from '../util/key-generator';
import CacheInstance, { AxiosCacheInstance, CacheProperties } from './types';

Expand All @@ -16,7 +16,7 @@ export function createCache(
axiosCache.generateKey = options.generateKey || defaultKeyGenerator;
axiosCache.waiting = options.waiting || {};
axiosCache.interpretHeader = options.interpretHeader || defaultHeaderInterpreter;

// CacheRequestConfig values
axiosCache.defaults = {
...axios.defaults,
Expand Down
3 changes: 2 additions & 1 deletion src/axios/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type {
Method
} from 'axios';
import { Deferred } from 'src/util/deferred';
import { KeyGenerator } from 'src/util/key-generator';
import { HeaderInterpreter } from '../header';
import { CachedResponse, CacheStorage } from '../storage/types';

Expand Down Expand Up @@ -92,7 +93,7 @@ export default interface CacheInstance {
* Defaults to a function that priorizes the id, and if not specified,
* a string is generated using the method, baseUrl, params, and url
*/
generateKey: (options: CacheRequestConfig) => string;
generateKey: KeyGenerator;

/**
* A simple object that holds all deferred objects until it is resolved.
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export * from './axios';
export * as Constants from './constants';
export * from './storage';
export * as StatusCodes from './util/status-codes';
4 changes: 2 additions & 2 deletions src/interceptors/request.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { CachedResponse } from 'src/storage/types';
import { AxiosCacheInstance } from '../axios/types';
import { CACHED_RESPONSE_STATUS, CACHED_RESPONSE_STATUS_TEXT } from '../constants';
import { Deferred } from '../util/deferred';
import { CACHED_RESPONSE_STATUS, CACHED_RESPONSE_STATUS_TEXT } from '../util/status-codes';

export function applyRequestInterceptor(axios: AxiosCacheInstance) {
export function applyRequestInterceptor(axios: AxiosCacheInstance): void {
axios.interceptors.request.use(async (config) => {
// Only cache specified methods
if (config.cache?.methods?.some((method) => (config.method || 'get').toLowerCase() == method)) {
Expand Down
12 changes: 7 additions & 5 deletions src/interceptors/response.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import { AxiosCacheInstance } from '../axios/types';
import { updateCache } from '../util/update-cache';

export function applyResponseInterceptor(axios: AxiosCacheInstance) {
export function applyResponseInterceptor(axios: AxiosCacheInstance): void {
axios.interceptors.response.use(async (response) => {
// Update other entries before updating himself
if (response.config.cache?.update) {
updateCache(axios, response.data, response.config.cache.update);
}

const shouldCache = response.config.cache?.shouldCache || axios.defaults.cache.shouldCache;

// Config told that this response should be cached.
if (!response.config.cache?.shouldCache!(response)) {
if (shouldCache(response)) {
return response;
}

Expand All @@ -24,14 +26,14 @@ export function applyResponseInterceptor(axios: AxiosCacheInstance) {

const defaultMaxAge = response.config.cache?.maxAge || axios.defaults.cache.maxAge;
cache.expiration = cache.expiration || defaultMaxAge;
let shouldCache = true;
let saveCache = true;

if (response.config.cache?.interpretHeader) {
const expirationTime = axios.interpretHeader(response.headers['cache-control']);

// Header told that this response should not be cached.
if (expirationTime === false) {
shouldCache = false;
saveCache = false;
} else {
cache.expiration = expirationTime ? expirationTime : defaultMaxAge;
}
Expand All @@ -45,7 +47,7 @@ export function applyResponseInterceptor(axios: AxiosCacheInstance) {
deferred.resolve(data);
}

if (shouldCache) {
if (saveCache) {
await axios.storage.set(key, {
data,
expiration: cache.expiration,
Expand Down
12 changes: 7 additions & 5 deletions src/util/deferred.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
export type MaybePromise<T> = T | PromiseLike<T>;

/**
* Represents the completion of an asynchronous operation that can be completed later.
*/
export class Deferred<T> {
readonly promise: Promise<T>;
private _resolve: (value: T | PromiseLike<T>) => void = () => {};
private _resolve: (value: MaybePromise<T>) => void = () => {};
private _reject: (reason?: any) => void = () => {};

constructor() {
Expand All @@ -17,7 +19,7 @@ export class Deferred<T> {
* Resolve this deferred promise with the given value.
* @param the value to resolve
*/
public readonly resolve = (value: T | PromiseLike<T>): void => {
public readonly resolve = (value: MaybePromise<T>): void => {
this._resolve(value);
};

Expand All @@ -36,8 +38,8 @@ export class Deferred<T> {
* @returns A Promise for the completion of which ever callback is executed.
*/
public readonly then = <TResult1 = T, TResult2 = never>(
onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null,
onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null
onfulfilled?: ((value: T) => MaybePromise<TResult1>) | undefined | null,
onrejected?: ((reason: any) => MaybePromise<TResult2>) | undefined | null
): Promise<TResult1 | TResult2> => {
return this.promise.then(onfulfilled, onrejected);
};
Expand All @@ -48,7 +50,7 @@ export class Deferred<T> {
* @returns A Promise for the completion of the callback.
*/
public readonly catch = <TResult = never>(
onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null
onrejected?: ((reason: any) => MaybePromise<TResult>) | undefined | null
): Promise<T | TResult> => {
return this.promise.catch(onrejected);
};
Expand Down
28 changes: 0 additions & 28 deletions src/util/interpret-header.ts

This file was deleted.

21 changes: 14 additions & 7 deletions src/util/key-generator.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
import { CacheRequestConfig } from '../axios/types';

export function defaultKeyGenerator({
export type KeyGenerator = (options: CacheRequestConfig) => string;

export const defaultKeyGenerator: KeyGenerator = ({
baseURL,
url,
method,
method: nullableMethod,
params,
id
}: CacheRequestConfig): string {
return id
? `id::${String(id)}`
: `${method?.toLowerCase() || 'get'}::${baseURL}::${url}::${JSON.stringify(params || '{}')}`;
}
}) => {
if (id) {
return `id::${String(id)}`;
}

const method = nullableMethod?.toLowerCase() || 'get';
const jsonParams = params ? JSON.stringify(params) : '{}';

return `${method}::${baseURL}::${url}::${jsonParams}`;
};
File renamed without changes.
2 changes: 1 addition & 1 deletion src/util/update-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export async function updateCache(
axios: AxiosCacheInstance,
data: any,
entries: CacheProperties['update']
) {
): Promise<void> {
for (const [cacheKey, value] of Object.entries(entries)) {
if (value == 'delete') {
await axios.storage.remove(cacheKey);
Expand Down

0 comments on commit d2c2a56

Please sign in to comment.