Skip to content

Commit

Permalink
4. Generate users model and service
Browse files Browse the repository at this point in the history
  • Loading branch information
sorrycc committed Feb 22, 2018
1 parent cb7a9c9 commit f511a77
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 10 deletions.
29 changes: 29 additions & 0 deletions src/pages/users/models/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import * as usersService from '../services/users';

export default {
namespace: 'users',
state: {
list: [],
total: null,
},
reducers: {
save(state, { payload: { data: list, total } }) {
return { ...state, list, total };
},
},
effects: {
*fetch({ payload: { page } }, { call, put }) {
const { data, headers } = yield call(usersService.fetch, { page });
yield put({ type: 'save', payload: { data, total: headers['x-total-count'] } });
},
},
subscriptions: {
setup({ dispatch, history }) {
return history.listen(({ pathname, query }) => {
if (pathname === '/users') {
dispatch({ type: 'fetch', payload: query });
}
});
},
},
};
5 changes: 5 additions & 0 deletions src/pages/users/services/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import request from '../../../utils/request';

export function fetch({ page = 1 }) {
return request(`/api/users?_page=${page}&_limit=5`);
}
27 changes: 17 additions & 10 deletions src/utils/request.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import fetch from 'dva/fetch';

function parseJSON(response) {
return response.json();
}

function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
Expand All @@ -21,10 +17,21 @@ function checkStatus(response) {
* @param {object} [options] The options we want to pass to "fetch"
* @return {object} An object containing either "data" or "err"
*/
export default function request(url, options) {
return fetch(url, options)
.then(checkStatus)
.then(parseJSON)
.then(data => ({ data }))
.catch(err => ({ err }));
export default async function request(url, options) {
const response = await fetch(url, options);

checkStatus(response);

const data = await response.json();

const ret = {
data,
headers: {},
};

if (response.headers.get('x-total-count')) {
ret.headers['x-total-count'] = response.headers.get('x-total-count');
}

return ret;
}

0 comments on commit f511a77

Please sign in to comment.