Skip to content

Instantly share code, notes, and snippets.

@uyu423
Created January 8, 2020 02:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uyu423/b3b70d48ed205529d761f3fe15ae0266 to your computer and use it in GitHub Desktop.
Save uyu423/b3b70d48ed205529d761f3fe15ae0266 to your computer and use it in GitHub Desktop.
import ioredis from 'ioredis';
import { DateTime } from 'luxon';
interface IRedisOption {
expire: number | false;
}
type IRedisResponse<T> = IRedisHaveDataSuccessResponse<T> | IRedisNotHaveDataSuccessResponse | IRedisFailureResponse;
interface IRedisCommonResponse {
duration: number;
key: string;
}
interface IRedisHaveDataSuccessResponse<T> extends IRedisCommonResponse {
success: true;
data: T;
}
interface IRedisNotHaveDataSuccessResponse extends IRedisCommonResponse {
success: true;
data: null;
}
interface IRedisFailureResponse extends IRedisCommonResponse {
success: false;
error: Error | null;
}
const defaultRedisOption: IRedisOption = {
expire: false,
};
export namespace RedisRepository {
export function get<T>(client: ioredis.Redis, key: string, _option: IRedisOption = defaultRedisOption) {
return async (): Promise<IRedisResponse<T>> => {
const start = DateTime.local();
try {
const result = await client.get(key);
if (result === null) {
const nullResponse: IRedisNotHaveDataSuccessResponse = {
key,
success: true,
data: null,
duration: start.diffNow().milliseconds * -1,
};
return nullResponse;
}
const redefined: T = (() => {
try {
return JSON.parse(result);
} catch {
return result;
}
})();
const response: IRedisHaveDataSuccessResponse<T> = {
key,
success: true,
data: redefined as T,
duration: start.diffNow().milliseconds * -1,
};
return response;
} catch (error) {
const response: IRedisFailureResponse = {
key,
error,
success: false,
duration: start.diffNow().milliseconds * -1,
};
return response;
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment