api-service.js 1.4 KB

123456789101112131415161718192021222324252627282930
  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. this.token = token
  16. this.opts.headers.authentication = `Bearer ${token}`
  17. }
  18. this.crud = (apiPrefix) => ({
  19. list: () => this.get(apiPrefix),
  20. create: data => this.post(apiPrefix, data),
  21. read: id => this.get(`${apiPrefix}/${id}`),
  22. update: (id, data) => this.patch(`${apiPrefix}/${id}`, data),
  23. delete: (id) => this.delete(`${apiPrefix}/${id}`),
  24. trash: () => this.get(`${apiPrefix}/trash`),
  25. undelete: (id) => this.delete(`${apiPrefix}/trash/${id}`),
  26. autocomplete: (searchText) => this.get(`${apiPrefix}`, { params: { q: searchText } })
  27. })
  28. })