| 12345678910111213141516171819202122232425262728293031323334353637 |
- const app = require('./app')
- app.service('api', function($http) {
- this.opts = {
- headers: {},
- withCredentials: true
- }
- this.postProcess = (res) => res.data
- this.get = (path, opts = {}) => $http.get(path, Object.assign({}, opts, this.opts)).then(this.postProcess)
- this.post = (path, data, opts = {}) => $http.post(path, data, Object.assign({}, opts, this.opts)).then(this.postProcess)
- this.put = (path, data, opts = {}) => $http.put(path, data, Object.assign({}, opts, this.opts)).then(this.postProcess)
- this.patch = (path, data, opts = {}) => $http.patch(path, data, Object.assign({}, opts, this.opts)).then(this.postProcess)
- this.delete = (path, opts = {}) => $http.delete(path, Object.assign({}, opts, this.opts)).then(this.postProcess)
- this.login = data => this.post('/api/auth/login', data)
- this.setToken = token => {
- localStorage.setItem('token', token)
- this.token = token
- this.opts.headers.authentication = `Bearer ${token}`
- }
- this.crud = (apiPrefix) => ({
- list: () => this.get(apiPrefix),
- create: data => this.post(apiPrefix, data),
- read: id => this.get(`${apiPrefix}/${id}`),
- update: (id, data) => this.patch(`${apiPrefix}/${id}`, data),
- delete: (id) => this.delete(`${apiPrefix}/${id}`),
- trash: () => this.get(`${apiPrefix}/trash`),
- undelete: (id) => this.delete(`${apiPrefix}/trash/${id}`),
- autocomplete: (searchText) => this.get(apiPrefix, { params: { q: searchText } }),
- lookup: (ids) => this.get(apiPrefix, { params: { ids: ids.join(',')}})
- })
- if (localStorage.getItem('token')) {
- this.setToken(localStorage.getItem('token'))
- }
- })
|