Advertisement
Guest User

Untitled

a guest
Sep 15th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. import axios, { AxiosAdapter, AxiosResponse } from "axios";
  2. import { createHash } from "crypto";
  3. import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
  4.  
  5. function str2Sha512(data: string) {
  6. const hash = createHash('sha512')
  7. hash.update(data)
  8. return hash.digest('hex');
  9. }
  10.  
  11. export const mfockAdapter: AxiosAdapter = async (config) => {
  12. const sha512 = str2Sha512(`${config.url} ${config.method}`);
  13.  
  14. const dir = `./.cache/`;
  15. mkdirSync(dir, {
  16. recursive: true
  17. })
  18. const cacheFilePath = `${dir}/${sha512}.json`;
  19.  
  20. if (existsSync(cacheFilePath)) {
  21. const cachedResponse: AxiosResponse = JSON.parse(readFileSync(cacheFilePath).toString('UTF-8'));
  22. return Promise.resolve(cachedResponse);
  23. } else {
  24. config.adapter = undefined; // disabled for calling own infinity
  25.  
  26. const response = await axios.request(config)
  27. writeFileSync(cacheFilePath, JSON.stringify({
  28. status: response.status,
  29. statusText: response.statusText,
  30. config: response.config,
  31. data: response.data,
  32. headers: response.headers,
  33. request: undefined//response.request
  34. }))
  35. return response;
  36. }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement