cloudDBAdapter.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import got from 'got';
  2. const stringify = (obj) => JSON.stringify(obj, null, 2);
  3. const parse = (str) => JSON.parse(str, (_, v) => {
  4. if (
  5. v !== null &&
  6. typeof v === 'object' &&
  7. 'type' in v &&
  8. v.type === 'Buffer' &&
  9. 'data' in v &&
  10. Array.isArray(v.data)) {
  11. return Buffer.from(v.data);
  12. }
  13. return v;
  14. });
  15. class CloudDBAdapter {
  16. constructor(url, {
  17. serialize = stringify,
  18. deserialize = parse,
  19. fetchOptions = {},
  20. } = {}) {
  21. this.url = url;
  22. this.serialize = serialize;
  23. this.deserialize = deserialize;
  24. this.fetchOptions = fetchOptions;
  25. }
  26. async read() {
  27. try {
  28. const res = await got(this.url, {
  29. method: 'GET',
  30. headers: {
  31. 'Accept': 'application/json;q=0.9,text/plain',
  32. },
  33. ...this.fetchOptions,
  34. });
  35. if (res.statusCode !== 200) throw res.statusMessage;
  36. return this.deserialize(res.body);
  37. } catch (e) {
  38. return null;
  39. }
  40. }
  41. async write(obj) {
  42. const res = await got(this.url, {
  43. method: 'POST',
  44. headers: {
  45. 'Content-Type': 'application/json',
  46. },
  47. ...this.fetchOptions,
  48. body: this.serialize(obj),
  49. });
  50. if (res.statusCode !== 200) throw res.statusMessage;
  51. return res.body;
  52. }
  53. }
  54. export default CloudDBAdapter;