Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

db.js 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. const domain = 'localhost'
  2. const port = 3001
  3. const httpProtocol = `http`
  4. const prefix = 'api'
  5. const remote = `${httpProtocol}://${domain}:${port}/${prefix}`
  6. const headerTemplate = {
  7. method: null,
  8. mode: 'cors', // no-cors, *cors, same-origin
  9. cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
  10. credentials: 'omit', // include, *same-origin, omit
  11. headers: {
  12. 'Content-Type': 'application/json',
  13. // 'Content-Type': 'application/x-www-form-urlencoded',
  14. },
  15. redirect: 'manual', // manual, *follow, error
  16. referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
  17. body: null, // body data type must match "Content-Type" header
  18. }
  19. class Connector {
  20. constructor() {
  21. this.apiPrefix = prefix
  22. this._verbs = {
  23. get: 'GET',
  24. post: 'POST',
  25. patch: 'PATCH',
  26. }
  27. }
  28. _makeHeader({ method, payload }) {
  29. const header = { ...headerTemplate }
  30. header.method = method
  31. if (payload) {
  32. header.body = JSON.stringify(payload)
  33. }
  34. return header
  35. }
  36. async _tryFetch({ endpoint, header }) {
  37. try {
  38. const res = await fetch(`${remote}${endpoint}`, header)
  39. if (!res.ok) {
  40. throw Error(res.statusText)
  41. }
  42. const jsonRes = await res.json()
  43. return jsonRes.data
  44. } catch (error) {
  45. console.error(`[API Util]: ${error}\nroute:`, endpoint)
  46. }
  47. }
  48. async get(endpoint) {
  49. return await this._tryFetch({
  50. endpoint,
  51. header: this._makeHeader({ method: this._verbs.get }),
  52. })
  53. }
  54. async post(endpoint, payload = {}) {
  55. return await this._tryFetch({
  56. endpoint,
  57. header: this._makeHeader({ method: this._verbs.post, payload }),
  58. })
  59. }
  60. async patch(endpoint, payload = {}) {
  61. return await this._tryFetch({
  62. endpoint,
  63. header: this._makeHeader({ method: this._verbs.patch, payload }),
  64. })
  65. }
  66. /** !: DEV ONLY */
  67. // async removeAll() { }
  68. }
  69. const db = new Connector()
  70. export { Connector, db, remote }