User.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import request from '../Utils/RequestUtils'
  2. import { addAsyncStorage, removeAsyncStorage } from '../Utils/AsyncStorageUtils'
  3. import submitPhone from '../Utils/FormUtils'
  4. import Toast from './Toast'
  5. const app = (now) => ({
  6. id: null,
  7. userInfo: {},
  8. getUser() {
  9. return request
  10. .get('/user/my')
  11. .then((res) => {
  12. now({
  13. id: res.id,
  14. userInfo: res,
  15. })
  16. })
  17. .catch((e) => {
  18. now({
  19. id: 0,
  20. })
  21. return Promise.reject(e)
  22. })
  23. },
  24. loginByPsd(phone, password) {
  25. const { loading, warnning, success } = now(Toast)
  26. loading()
  27. return request
  28. .post('/auth/login', {
  29. data: {
  30. username: submitPhone(phone),
  31. password,
  32. },
  33. requestType: 'form',
  34. })
  35. .then((res) => {
  36. return addAsyncStorage('token', res)
  37. })
  38. .then(() => {
  39. const { getUser } = now()
  40. return getUser()
  41. })
  42. .then(() => {
  43. success('登录成功')
  44. })
  45. .catch((e) => {
  46. warnning(e.error)
  47. })
  48. },
  49. logout() {
  50. const { loading, success } = now(Toast)
  51. loading()
  52. // 移除 token
  53. return removeAsyncStorage('token').then(() => {
  54. // 清除用户信息
  55. now({ id: 0, userInfo: {} })
  56. success('退出成功')
  57. })
  58. },
  59. })
  60. export default app