项目作者: Araekiel

项目描述 :
An npm module for in-memory automated API caching.
高级语言: TypeScript
项目地址: git://github.com/Araekiel/mastak.git
创建时间: 2020-07-31T20:47:34Z
项目社区:https://github.com/Araekiel/mastak

开源协议:MIT License

下载


Mastak


An npm package for automated, in-memory API caching.


Built with TypeScript.


Release
Github Release


About
Installation
Initialization
Types
Usage
License

About

An npm module to automate the regular processing and caching of responses from APIs. With a caching mechanism inspired by node-cache, this module has all the standard interface methods to interact with the in-memory cache.

Mastak makes requests using node-fetch and processes the response based on the resProcessor() function provided by the user. Each key gets a timeout(ttl) and an updateInterval(if autoUpdate is true).

Installation

  1. $ npm install mastak --save

Initialization

  1. const Mastak = require("mastak");
  2. const cache = new Mastak();

To import the module in TypeScript, esModuleInterop needs to be set to true in your tsconfig.json.

Options

  • stdTTL: (default: 0) - the standard timeout(in seconds) for each element of the cache, 0 = infinite.
  • autoUpdate: (default: true) - boolean flag that states if each element in the cache has to be regularly updated or not.
  • updateInterval: (default: 3600(1 hr in secs)) - the standard interval(in seconds) at which each element in the cache has to be updated.
  • checkPeriod: (default: 600(10 min in secs)) - the regular interval(in seconds) at which the internal checkData() method will check each element for timeout and autoUpdate.

Example

  1. const Mastak = require("mastak");
  2. const cache = new Mastak({
  3. stdTTL: 1800,
  4. updateInterval: 7200,
  5. });

Types

There are 3 types/interfaces that a user has to take into account when using Mastak, i.e. Request, CacheInput & CacheUnit.

Request & CacheInput define the format of input that is expected from the user while CacheUnit defines the format in which an API and its value is stored within the cache.

Request

Request defines the data needed to form a valid request that can be sent using node-fetch.

  1. interface Request {
  2. url: string; // url for the api
  3. method: string; // http method to be used
  4. body?: {
  5. [key: string]: any; // body for the request
  6. };
  7. headers?: {
  8. [key: string]: string; // headers
  9. };
  10. }

CacheInput

CacheInput defines all the data that needs to be input to set or update an API.

  1. interface CacheInput {
  2. request: Request;
  3. resProcessor?: any; // a function that processes the response recieved
  4. updateInterval?: number; // the interval over which the API needs to be updated
  5. ttl?: number; // the timeout for the API
  6. }

CacheUnit

CacheUnit defines the format in which an API is stored in the cache. It extends CacheInput i.e. it inherits all its properties.

  1. interface CacheUnit extends CacheInput {
  2. setTime: number; // the time at which this API/CacheUnit was set
  3. lastUpdate: number; // the time at which the value was last updated
  4. value: any; // the processed response from the API
  5. }

? - field is not required.

Take a look at src/types/main.interfaces.ts to see all the defined interfaces.

Usage

set()

Set an API or CacheUnit in the cache with the key provided.
Returns a promise that resolves with the entire CacheUnit stored against a key or rejects an error.

  1. Mastak.set((key: string), (api: CacheInput));

Example

  1. const request = {
  2. url: "https://jsonplaceholder.typicode.com/posts",
  3. method: "POST",
  4. body: {
  5. title: "foo",
  6. body: "bar",
  7. userId: 1,
  8. },
  9. headers: {
  10. "Content-type": "application/json; charset=UTF-8",
  11. },
  12. };
  13. const api = {
  14. request: request,
  15. ttl: 1800,
  16. };
  17. const foo = async () => {
  18. try {
  19. let response = await cache.set("JSONPlaceholder", api);
  20. console.log("set()", response);
  21. } catch (err) {
  22. console.warn(err.message);
  23. }
  24. };
  25. foo();

Output

  1. set() { setTime: 1621113414640,
  2. lastUpdate: 1621113414640,
  3. value: { title: 'foo', body: 'bar', userId: 1, id: 101 },
  4. request:
  5. { url: 'https://jsonplaceholder.typicode.com/posts',
  6. method: 'POST',
  7. body: { title: 'foo', body: 'bar', userId: 1 },
  8. headers: { 'Content-type': 'application/json; charset=UTF-8' } } }

get()

Get the currently stored value for an API with the key.
Returns the “value” for the CacheUnit or throws a BadKey error.

  1. Mastak.get((key: string));

Example

  1. try {
  2. let response = await cache.get("JSONPlaceholder");
  3. console.log("get()", response);
  4. } catch (err) {
  5. console.warn(err.message);
  6. }

Output

  1. get() { title: 'foo', body: 'bar', userId: 1, id: 101 }

update()

Update the data of a CacheUnit and update its value if updateNow argument is true.

Returns a promise that resolves with the updated CacheUnit or rejects an error.

  1. Mastak.update((key: string), (api: CacheInput), (updateNow: boolean));

Example

  1. const request2 = {
  2. url: "https://jsonplaceholder.typicode.com/posts/2",
  3. method: "PATCH",
  4. body: {
  5. title: "foo",
  6. },
  7. };
  8. const resProcessor2 = (data) => {
  9. return data.userId;
  10. };
  11. const api2 = {
  12. request: request2,
  13. resProcessor: resProcessor2,
  14. };
  15. const foo = async () => {
  16. try {
  17. response = await cache.update("JSONPlaceholder", api2, true);
  18. console.log("update()", response);
  19. } catch (err) {
  20. console.warn(err.message);
  21. }
  22. };
  23. foo();

Output

  1. update() { setTime: 1621113648549,
  2. lastUpdate: 1621113649233,
  3. value: 1,
  4. request:
  5. { url: 'https://jsonplaceholder.typicode.com/posts/2',
  6. method: 'PATCH',
  7. body: { title: 'foo' } },
  8. resProcessor: [Function: something2] }

delete()

Delete a CacheUnit with the key.

Returns boolean - true if successful or throws a BadKey error

  1. Mastak.delete((key: string));

Example

  1. try {
  2. let response = await cache.delete("JSONPlaceholder");
  3. console.log("delete()", response);
  4. } catch (err) {
  5. console.warn(err.message);
  6. }

Output

  1. delete() true

setMulti()

Set multiple APIs or CacheUnits in the cache with arrays of keys and CacheInputs.

Returns a promise that resolves with an array of proccessed CacheUnits or rejects an error.

  1. Mastak.setMulti((keys: Array<string>), (apis: Array<CacheInput>));

Example

  1. const request = {
  2. url: "https://jsonplaceholder.typicode.com/posts",
  3. method: "POST",
  4. body: {
  5. title: "foo",
  6. body: "bar",
  7. userId: 1,
  8. },
  9. headers: {
  10. "Content-type": "application/json; charset=UTF-8",
  11. },
  12. };
  13. const request2 = {
  14. url: "https://jsonplaceholder.typicode.com/posts/2",
  15. method: "PATCH",
  16. body: {
  17. title: "foo",
  18. },
  19. };
  20. const resProcessor2 = (data) => {
  21. return data.userId;
  22. };
  23. const api: CacheInput = {
  24. request: request,
  25. ttl: 1800,
  26. };
  27. const api2 = {
  28. request: request2,
  29. resProcessor: resProcessor2,
  30. };
  31. const foo = async () => {
  32. try {
  33. let response = await cache.setMulti(
  34. ["JSONPlaceholder", "JSONPlaceholder2"],
  35. [api, api2]
  36. );
  37. console.log("setMulti()", response);
  38. } catch (err) {
  39. console.warn(err.message);
  40. }
  41. };
  42. foo();

Output

  1. setMulti()[
  2. ({
  3. setTime: 1621113734595,
  4. lastUpdate: 1621113734595,
  5. value: { title: "foo", body: "bar", userId: 1, id: 101 },
  6. request: {
  7. url: "https://jsonplaceholder.typicode.com/posts",
  8. method: "POST",
  9. body: [Object],
  10. headers: [Object],
  11. },
  12. },
  13. {
  14. setTime: 1621113735169,
  15. lastUpdate: 1621113735169,
  16. value: 1,
  17. request: {
  18. url: "https://jsonplaceholder.typicode.com/posts/2",
  19. method: "PATCH",
  20. body: [Object],
  21. },
  22. resProcessor: [(Function: something2)],
  23. })
  24. ];

getMulti()

Get current value of multiple CacheUnits with an array of keys.

Returns an array of values or throws a BadKey error.

  1. Mastak.getMulti((keys: Array<string>));

Example

  1. try {
  2. let response = cache.getMulti(["JSONPlaceholder", "JSONPlaceholder2"]);
  3. console.log("getMulti()", response);
  4. } catch (err) {
  5. console.warn(err.message);
  6. }

Output

  1. getMulti() { JSONPlaceholder: { title: 'foo', body: 'bar', userId: 1, id: 101 },
  2. JSONPlaceholder2: 1 }

has()

Checks if the cache contains a key or not.

Returns boolean - true or false

  1. Mastak.has((key: string));

Example

  1. let response = cache.has("JSONPlaceholder");
  2. console.log("has()", response);

Output

  1. has() true

keys()

Get all the keys currently stored in the cache.

Returns an array of strings(keys).

  1. Mastak.keys();

Example

  1. let response = cache.keys();
  2. console.log("keys()", response);

Output

  1. keys()[("JSONPlaceholder", "JSONPlaceholder2")];

deleteMulti()

Delete multiple CacheUnits with an array of keys.

Returns boolean - true if successful or throws a BadKey error.

  1. Mastak.deleteMulti((keys: Array<string>));

Example

  1. try {
  2. let response = cache.deleteMulti(["JSONPlaceholder", "JSONPlaceholder2"]);
  3. console.log("deleteMulti()", response);
  4. } catch (err) {
  5. console.warn(err.message);
  6. }

Output

  1. deleteMulti() true

take()

Delete a CacheUnit and return its value.

Returns the deleted CacheUnit or throws a BadKey error.

  1. Mastak.take((key: string));

Example

  1. try {
  2. let response = cache.take("JSONPlaceholder");
  3. console.log("take()", response);
  4. } catch (err) {
  5. console.warn(err.message);
  6. }

Output

  1. take() { setTime: 1621113915875,
  2. lastUpdate: 1621113915875,
  3. value: { title: 'foo', body: 'bar', userId: 1, id: 101 },
  4. request:
  5. { url: 'https://jsonplaceholder.typicode.com/posts',
  6. method: 'POST',
  7. body: { title: 'foo', body: 'bar', userId: 1 },
  8. headers: { 'Content-type': 'application/json; charset=UTF-8' } } }

flush()

Delete all the data in the cache.

Returns boolean - true.

  1. Mastak.flush();

Example

  1. let response = cache.flush();
  2. console.log("flush()", response);

Output

  1. flush() true

License

MIT License | Copyright (c) 2024 Kumar Shashwat