api-service.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. const decode = require('jsonwebtoken/decode')
  2. const app = require('./app')
  3. app.service('api', function($http) {
  4. window.api = this
  5. this.opts = {
  6. headers: {},
  7. withCredentials: true
  8. }
  9. this.claims = {}
  10. this.postProcess = (res) => res.data
  11. this.get = (path, opts = {}) => $http.get(path, Object.assign({}, opts, this.opts)).then(this.postProcess)
  12. this.post = (path, data, opts = {}) => $http.post(path, data, Object.assign({}, opts, this.opts)).then(this.postProcess)
  13. this.put = (path, data, opts = {}) => $http.put(path, data, Object.assign({}, opts, this.opts)).then(this.postProcess)
  14. this.patch = (path, data, opts = {}) => $http.patch(path, data, Object.assign({}, opts, this.opts)).then(this.postProcess)
  15. this.delete = (path, opts = {}) => $http.delete(path, Object.assign({}, opts, this.opts)).then(this.postProcess)
  16. const setUser = (user, token) => {
  17. const decoded = decode(token)
  18. this.token = token
  19. this.user = user
  20. this.claims = decoded
  21. this.opts.headers.authentication = `Bearer ${token}`
  22. localStorage.setItem('token', token)
  23. localStorage.setItem('user', JSON.stringify(user))
  24. }
  25. const clearUser = () => {
  26. this.token = null
  27. this.user = null
  28. this.claims = {}
  29. delete this.opts.headers.authentication
  30. localStorage.removeItem('token')
  31. localStorage.removeItem('user')
  32. }
  33. this.login = async data => {
  34. const res = await this.post('/api/auth/login', data)
  35. setUser(res.user, res.token)
  36. }
  37. this.logout = async () => {
  38. clearUser()
  39. }
  40. this.restore = () => {
  41. const token = localStorage.getItem('token')
  42. const userJson = localStorage.getItem('user')
  43. if (token && userJson) {
  44. try {
  45. const user = JSON.parse(userJson)
  46. setUser(user, token)
  47. } catch (err) {
  48. console.warn(`Unable to restore login:`, err)
  49. }
  50. }
  51. }
  52. this.restore()
  53. this.crud = (apiPrefix) => ({
  54. list: () => this.get(apiPrefix),
  55. create: data => this.post(apiPrefix, data),
  56. read: id => this.get(`${apiPrefix}/${id}`),
  57. update: (id, data) => this.patch(`${apiPrefix}/${id}`, data),
  58. delete: (id) => this.delete(`${apiPrefix}/${id}`),
  59. trash: () => this.get(`${apiPrefix}/trash`),
  60. undelete: (id) => this.delete(`${apiPrefix}/trash/${id}`),
  61. autocomplete: (searchText) => this.get(apiPrefix, { params: { q: searchText } }),
  62. lookup: (ids) => this.get(apiPrefix, { params: { ids: ids.join(',')}})
  63. })
  64. })