store.uts 2.2 KB
Newer Older
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
1
export type State = {
crlfe's avatar
crlfe 已提交
2 3 4
  pendingAgreements: boolean,
  isLogin: boolean,
  userInfo: UTSJSONObject
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
5 6 7
}
// 实例化为state
export const state = reactive({
crlfe's avatar
crlfe 已提交
8 9 10 11 12 13 14 15
  pendingAgreements: false,
  userInfo: {
    "_id": null,
    "avatar_file": null,
    "nickname": null,
    "mobile": null,
  } as UTSJSONObject,
  isLogin: false
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
16 17 18
} as State)

function initState() {
crlfe's avatar
crlfe 已提交
19 20 21 22
  try {
    let userInfo = uni.getStorageSync('uni-id-pages-x-userInfo')
    if (userInfo instanceof UTSJSONObject) {
      state.userInfo = userInfo
A
Anne_LXM 已提交
23
      console.log('init userInfo',userInfo);
crlfe's avatar
crlfe 已提交
24 25 26 27 28
    }
  } catch (e) {
    console.error('init userInfo error', e);
  }
  state.isLogin = uniCloud.getCurrentUserInfo().tokenExpired > Date.now()
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
29 30 31 32 33
};
initState()


type Mutations = {
crlfe's avatar
crlfe 已提交
34
  updateUserInfo(param: null | UTSJSONObject): void
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
35 36
}
export const mutations = {
A
Anne_LXM 已提交
37
  updateUserInfo: function (param: null | UTSJSONObject) {
A
Anne_LXM 已提交
38
    //console.log('updateUserInfo', param); // param为 null 时从云端获取数据更新,为UTSJSONObject时直接根据传入的值来更新
crlfe's avatar
crlfe 已提交
39 40 41 42 43 44 45 46
    function afterUpdateUserInfo() {
      // console.log('afterUpdateUserInfo', state.userInfo);
      uni.setStorageSync('uni-id-pages-x-userInfo', state.userInfo)
    }

    if (param == null) {
      const db = uniCloud.databaseForJQL()
      const user_id = uniCloud.getCurrentUserInfo().uid
A
Anne_LXM 已提交
47
      console.log('user_id', user_id);
crlfe's avatar
crlfe 已提交
48 49 50 51 52
      if (user_id != null) {
        db.collection('uni-id-users')
          .doc(user_id)
          .field('_id,username,nickname,avatar_file,mobile')
          .get()
A
Anne_LXM 已提交
53
          .then(res => {
crlfe's avatar
crlfe 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67
            const uniIdCo = uniCloud.importObject('uni-id-co', {
              customUI: true
            })

            uniIdCo
                .getRealNameInfo()
                .then((realNameInfo) => {
              state.userInfo = Object.assign(res.data[0], {
                realNameInfo
              })

              afterUpdateUserInfo()
            })
          })
A
Anne_LXM 已提交
68
          .catch((err: any | null) => {
crlfe's avatar
crlfe 已提交
69 70 71 72 73 74 75 76 77 78 79 80
            const error = err as UniCloudError
            console.error(error.errMsg, '错误')
          })
      }
    } else {
      param.toMap().forEach((value, key) => {
        state.userInfo.set(key, value)
      })
      afterUpdateUserInfo()
    }
  }
} as Mutations;