api-service.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. const app = require('./app')
  2. app.service('api', function($http) {
  3. this.opts = {
  4. headers: {},
  5. withCredentials: true
  6. }
  7. this.postProcess = (res) => res.data
  8. this.get = (path, opts = {}) => $http.get(path, Object.assign({}, opts, this.opts)).then(this.postProcess)
  9. this.post = (path, data, opts = {}) => $http.post(path, data, Object.assign({}, opts, this.opts)).then(this.postProcess)
  10. this.put = (path, data, opts = {}) => $http.put(path, data, Object.assign({}, opts, this.opts)).then(this.postProcess)
  11. this.patch = (path, data, opts = {}) => $http.patch(path, data, Object.assign({}, opts, this.opts)).then(this.postProcess)
  12. this.delete = (path, opts = {}) => $http.delete(path, Object.assign({}, opts, this.opts)).then(this.postProcess)
  13. this.login = data => this.post('/api/auth/login', data)
  14. this.setToken = token => {
  15. localStorage.setItem('token', token)
  16. this.token = token
  17. this.opts.headers.authentication = `Bearer ${token}`
  18. }
  19. this.crud = (apiPrefix) => ({
  20. list: () => this.get(apiPrefix),
  21. create: data => this.post(apiPrefix, data),
  22. read: id => this.get(`${apiPrefix}/${id}`),
  23. update: (id, data) => this.patch(`${apiPrefix}/${id}`, data),
  24. delete: (id) => this.delete(`${apiPrefix}/${id}`),
  25. trash: () => this.get(`${apiPrefix}/trash`),
  26. undelete: (id) => this.delete(`${apiPrefix}/trash/${id}`),
  27. autocomplete: (searchText) => this.get(apiPrefix, { params: { q: searchText } }),
  28. lookup: (ids) => this.get(apiPrefix, { params: { ids: ids.join(',')}})
  29. })
  30. if (localStorage.getItem('token')) {
  31. this.setToken(localStorage.getItem('token'))
  32. }
  33. })