feat: 开发收藏和下载功能
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
const cloud = require('wx-server-sdk');
|
||||
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
|
||||
|
||||
const db = cloud.database();
|
||||
const command = db.command;
|
||||
|
||||
exports.main = async (event) => {
|
||||
const wxContext = cloud.getWXContext();
|
||||
const openid = wxContext.OPENID;
|
||||
|
||||
// 获取 userId
|
||||
const { data: users } = await db
|
||||
.collection('users')
|
||||
.where({ openid })
|
||||
.limit(1)
|
||||
.get();
|
||||
|
||||
if (users.length === 0) {
|
||||
return { code: -1, message: '用户未登录' };
|
||||
}
|
||||
|
||||
const userId = users[0]._id;
|
||||
const { action } = event;
|
||||
|
||||
switch (action) {
|
||||
case 'add':
|
||||
return await handleAdd(userId, event);
|
||||
case 'list':
|
||||
return await handleList(userId, event);
|
||||
default:
|
||||
return { code: -1, message: '未知操作' };
|
||||
}
|
||||
};
|
||||
|
||||
async function handleAdd(userId, event) {
|
||||
const { worksheetId } = event;
|
||||
if (!worksheetId) return { code: -1, message: 'worksheetId 不能为空' };
|
||||
|
||||
const collection = db.collection('download_logs');
|
||||
|
||||
const record = {
|
||||
userId,
|
||||
worksheetId,
|
||||
createdAt: db.serverDate(),
|
||||
};
|
||||
const { _id } = await collection.add({ data: record });
|
||||
|
||||
// worksheets.downloads +1
|
||||
try {
|
||||
await db.collection('worksheets').doc(worksheetId).update({
|
||||
data: {
|
||||
downloads: command.inc(1),
|
||||
updatedAt: db.serverDate(),
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn('更新 worksheets.downloads 失败', e);
|
||||
}
|
||||
|
||||
return { code: 0, data: { _id, ...record } };
|
||||
}
|
||||
|
||||
async function handleList(userId, event) {
|
||||
const { page = 1, pageSize = 20 } = event;
|
||||
const skip = (page - 1) * pageSize;
|
||||
|
||||
const collection = db.collection('download_logs');
|
||||
|
||||
const { data: logs } = await collection
|
||||
.where({ userId })
|
||||
.orderBy('createdAt', 'desc')
|
||||
.skip(skip)
|
||||
.limit(pageSize)
|
||||
.get();
|
||||
|
||||
if (logs.length === 0) {
|
||||
return { code: 0, data: [] };
|
||||
}
|
||||
|
||||
// 关联查询 worksheets 信息
|
||||
const worksheetIds = [...new Set(logs.map((l) => l.worksheetId))];
|
||||
const { data: worksheets } = await db
|
||||
.collection('worksheets')
|
||||
.where({ _id: command.in(worksheetIds) })
|
||||
.get();
|
||||
|
||||
const worksheetMap = {};
|
||||
worksheets.forEach((w) => {
|
||||
worksheetMap[w._id] = w;
|
||||
});
|
||||
|
||||
const result = logs.map((l) => ({
|
||||
...l,
|
||||
worksheet: worksheetMap[l.worksheetId] || null,
|
||||
}));
|
||||
|
||||
return { code: 0, data: result };
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "user-download-logs",
|
||||
"version": "1.0.0",
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"wx-server-sdk": "^3.0.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
const cloud = require('wx-server-sdk');
|
||||
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
|
||||
|
||||
const db = cloud.database();
|
||||
const command = db.command;
|
||||
|
||||
exports.main = async (event) => {
|
||||
const wxContext = cloud.getWXContext();
|
||||
const openid = wxContext.OPENID;
|
||||
|
||||
// 获取 userId
|
||||
const { data: users } = await db
|
||||
.collection('users')
|
||||
.where({ openid })
|
||||
.limit(1)
|
||||
.get();
|
||||
|
||||
if (users.length === 0) {
|
||||
return { code: -1, message: '用户未登录' };
|
||||
}
|
||||
|
||||
const userId = users[0]._id;
|
||||
const { action } = event;
|
||||
|
||||
switch (action) {
|
||||
case 'add':
|
||||
return await handleAdd(userId, event);
|
||||
case 'remove':
|
||||
return await handleRemove(userId, event);
|
||||
case 'list':
|
||||
return await handleList(userId, event);
|
||||
case 'check':
|
||||
return await handleCheck(userId, event);
|
||||
case 'batchCheck':
|
||||
return await handleBatchCheck(userId, event);
|
||||
default:
|
||||
return { code: -1, message: '未知操作' };
|
||||
}
|
||||
};
|
||||
|
||||
async function handleAdd(userId, event) {
|
||||
const { worksheetId } = event;
|
||||
if (!worksheetId) return { code: -1, message: 'worksheetId 不能为空' };
|
||||
|
||||
const collection = db.collection('favorites');
|
||||
|
||||
// 幂等检查:已收藏则直接返回
|
||||
const { data: existing } = await collection
|
||||
.where({ userId, worksheetId })
|
||||
.limit(1)
|
||||
.get();
|
||||
|
||||
if (existing.length > 0) {
|
||||
return { code: 0, data: existing[0], message: '已收藏' };
|
||||
}
|
||||
|
||||
// 写入收藏记录
|
||||
const record = {
|
||||
userId,
|
||||
worksheetId,
|
||||
createdAt: db.serverDate(),
|
||||
};
|
||||
const { _id } = await collection.add({ data: record });
|
||||
|
||||
// worksheets.likes +1
|
||||
try {
|
||||
await db
|
||||
.collection('worksheets')
|
||||
.doc(worksheetId)
|
||||
.update({
|
||||
data: {
|
||||
likes: command.inc(1),
|
||||
updatedAt: db.serverDate(),
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn('更新 worksheets.likes 失败', e);
|
||||
}
|
||||
|
||||
return { code: 0, data: { _id, ...record } };
|
||||
}
|
||||
|
||||
async function handleRemove(userId, event) {
|
||||
const { worksheetId } = event;
|
||||
if (!worksheetId) return { code: -1, message: 'worksheetId 不能为空' };
|
||||
|
||||
const collection = db.collection('favorites');
|
||||
|
||||
const { data: existing } = await collection
|
||||
.where({ userId, worksheetId })
|
||||
.limit(1)
|
||||
.get();
|
||||
|
||||
if (existing.length === 0) {
|
||||
return { code: 0, message: '未收藏' };
|
||||
}
|
||||
|
||||
await collection.doc(existing[0]._id).remove();
|
||||
|
||||
// worksheets.likes -1
|
||||
try {
|
||||
await db
|
||||
.collection('worksheets')
|
||||
.doc(worksheetId)
|
||||
.update({
|
||||
data: {
|
||||
likes: command.inc(-1),
|
||||
updatedAt: db.serverDate(),
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn('更新 worksheets.likes 失败', e);
|
||||
}
|
||||
|
||||
return { code: 0, message: '已取消收藏' };
|
||||
}
|
||||
|
||||
async function handleList(userId, event) {
|
||||
const { page = 1, pageSize = 20 } = event;
|
||||
const skip = (page - 1) * pageSize;
|
||||
|
||||
const collection = db.collection('favorites');
|
||||
|
||||
// 查询收藏记录
|
||||
const { data: favorites } = await collection
|
||||
.where({ userId })
|
||||
.orderBy('createdAt', 'desc')
|
||||
.skip(skip)
|
||||
.limit(pageSize)
|
||||
.get();
|
||||
|
||||
if (favorites.length === 0) {
|
||||
return { code: 0, data: [] };
|
||||
}
|
||||
|
||||
// 关联查询 worksheets 信息
|
||||
const worksheetIds = favorites.map((f) => f.worksheetId);
|
||||
const { data: worksheets } = await db
|
||||
.collection('worksheets')
|
||||
.where({ _id: command.in(worksheetIds) })
|
||||
.get();
|
||||
|
||||
const worksheetMap = {};
|
||||
worksheets.forEach((w) => {
|
||||
worksheetMap[w._id] = w;
|
||||
});
|
||||
|
||||
const result = favorites.map((f) => ({
|
||||
...f,
|
||||
worksheet: worksheetMap[f.worksheetId] || null,
|
||||
}));
|
||||
|
||||
return { code: 0, data: result };
|
||||
}
|
||||
|
||||
async function handleCheck(userId, event) {
|
||||
const { worksheetId } = event;
|
||||
if (!worksheetId) return { code: -1, message: 'worksheetId 不能为空' };
|
||||
|
||||
const { data } = await db
|
||||
.collection('favorites')
|
||||
.where({ userId, worksheetId })
|
||||
.limit(1)
|
||||
.get();
|
||||
|
||||
return { code: 0, data: { favorited: data.length > 0 } };
|
||||
}
|
||||
|
||||
async function handleBatchCheck(userId, event) {
|
||||
const { worksheetIds } = event;
|
||||
if (
|
||||
!worksheetIds ||
|
||||
!Array.isArray(worksheetIds) ||
|
||||
worksheetIds.length === 0
|
||||
) {
|
||||
return { code: 0, data: {} };
|
||||
}
|
||||
|
||||
const { data } = await db
|
||||
.collection('favorites')
|
||||
.where({ userId, worksheetId: command.in(worksheetIds) })
|
||||
.get();
|
||||
|
||||
const favoritedMap = {};
|
||||
data.forEach((item) => {
|
||||
favoritedMap[item.worksheetId] = true;
|
||||
});
|
||||
|
||||
return { code: 0, data: favoritedMap };
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "user-favorites",
|
||||
"version": "1.0.0",
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"wx-server-sdk": "^3.0.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
const cloud = require('wx-server-sdk');
|
||||
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
|
||||
|
||||
const db = cloud.database();
|
||||
|
||||
exports.main = async (event, context) => {
|
||||
const wxContext = cloud.getWXContext();
|
||||
const openid = wxContext.OPENID;
|
||||
const unionid = wxContext.UNIONID || null;
|
||||
|
||||
const { action } = event;
|
||||
|
||||
switch (action) {
|
||||
case 'updateProfile':
|
||||
return await handleUpdateProfile(event, openid);
|
||||
default:
|
||||
return await handleSilentLogin(openid, unionid);
|
||||
}
|
||||
};
|
||||
|
||||
async function handleSilentLogin(openid, unionid) {
|
||||
const usersCollection = db.collection('users');
|
||||
|
||||
const { data } = await usersCollection.where({ openid }).limit(1).get();
|
||||
|
||||
const now = db.serverDate();
|
||||
|
||||
if (data.length > 0) {
|
||||
const user = data[0];
|
||||
const updateData = { lastActiveAt: now };
|
||||
if (unionid && !user.unionid) {
|
||||
updateData.unionid = unionid;
|
||||
}
|
||||
await usersCollection.doc(user._id).update({ data: updateData });
|
||||
|
||||
return {
|
||||
code: 0,
|
||||
data: { ...user, ...updateData, lastActiveAt: new Date() },
|
||||
};
|
||||
} else {
|
||||
const newUser = {
|
||||
openid,
|
||||
unionid,
|
||||
nickName: null,
|
||||
avatarUrl: null,
|
||||
totalDownloads: 0,
|
||||
createdAt: now,
|
||||
lastActiveAt: now,
|
||||
};
|
||||
const { _id } = await usersCollection.add({ data: newUser });
|
||||
|
||||
return {
|
||||
code: 0,
|
||||
data: {
|
||||
_id,
|
||||
...newUser,
|
||||
createdAt: new Date(),
|
||||
lastActiveAt: new Date(),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function handleUpdateProfile(event, openid) {
|
||||
const { nickName, avatarUrl } = event;
|
||||
const usersCollection = db.collection('users');
|
||||
|
||||
const { data } = await usersCollection.where({ openid }).limit(1).get();
|
||||
|
||||
if (data.length === 0) {
|
||||
return { code: -1, message: '用户不存在' };
|
||||
}
|
||||
|
||||
const updateData = {};
|
||||
if (nickName !== undefined) updateData.nickName = nickName;
|
||||
if (avatarUrl !== undefined) updateData.avatarUrl = avatarUrl;
|
||||
|
||||
await usersCollection.doc(data[0]._id).update({ data: updateData });
|
||||
|
||||
return {
|
||||
code: 0,
|
||||
data: { ...data[0], ...updateData },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "user-login",
|
||||
"version": "1.0.0",
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"wx-server-sdk": "^3.0.4"
|
||||
}
|
||||
}
|
||||
@@ -126,13 +126,12 @@
|
||||
对应 Prisma `User`(`@@map("users")`)。**`openid` / `unionid` 与 `_id` 的取舍、`unionid` 写入方式**见 §3.2。
|
||||
|
||||
| 字段 | BSON 类型 | 必填 | 说明 |
|
||||
| ---------------- | -------------- | ---- | ----------------------------------------------------------------------------------------------------- |
|
||||
| -------------- | -------------- | ---- | ----------------------------------------------------------------------------------------------------- | ----- |
|
||||
| `_id` | string | 是 | 主键;可与 Prisma `User.id` 一样使用 cuid,也可自定义为其它字符串,团队内与用户档案查询方式统一即可。 |
|
||||
| `openid` | string | 是 | 当前小程序下微信用户标识;与 Prisma 一致建议 ≤100 字符;**业务唯一**,索引见下表。 |
|
||||
| `unionid` | string \| null | 否 | 开放平台下跨应用用户标识;建议 ≤100 字符;未绑开放平台或未返回时为空。 |
|
||||
| `nickName` | string \| null | 否 | 用户昵称;建议 ≤50 字符。 |
|
||||
| `avatarUrl` | string \| null | 否 | 头像 URL 或云存储 fileID;建议 ≤500 字符。 |
|
||||
| `totalDownloads` | int | 是 | 累计下载次数,默认 `0`。 |
|
||||
| `avatarUrl` | string \| null | 否 | 头像 URL 或云存储 fileID;建议 ≤500 字符。 | `0`。 |
|
||||
| `createdAt` | date | 是 | 首次创建时间。 |
|
||||
| `lastActiveAt` | date | 是 | 最近一次活跃时间(登录、打开小程序、写库等策略由实现约定)。 |
|
||||
|
||||
@@ -145,7 +144,7 @@
|
||||
|
||||
---
|
||||
|
||||
### 3.6 集合:`favorites`(收藏日志)
|
||||
### 3.6 集合:`favorites_log`(收藏日志)
|
||||
|
||||
对应 Prisma `FavoriteLog`。
|
||||
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
# 用户登录与信息授权方案
|
||||
|
||||
> 版本:v1.0
|
||||
> 最后更新:2026-05-06
|
||||
> 适用范围:微信小程序云开发环境下的用户身份管理
|
||||
|
||||
---
|
||||
|
||||
## 一、方案概述
|
||||
|
||||
采用**静默登录**策略:用户进入小程序后无感知地完成身份识别与用户创建,不弹出任何授权弹窗。昵称和头像等个人信息在后续需要时(如个人中心、评论等场景)再引导用户主动授权。
|
||||
|
||||
**核心流程**:
|
||||
|
||||
```
|
||||
用户打开小程序
|
||||
│
|
||||
├─ 本地 Storage 有用户数据且未过期?
|
||||
│ │
|
||||
│ ├─ 是 → 直接使用本地数据,跳过登录
|
||||
│ │
|
||||
│ └─ 否 → 调用云函数 silentLogin
|
||||
│ │
|
||||
│ ├─ cloud.getWXContext() 获取 openid/unionid
|
||||
│ │
|
||||
│ ├─ 查询 users 集合(openid)
|
||||
│ │ │
|
||||
│ │ ├─ 存在 → 更新 lastActiveAt,返回用户数据
|
||||
│ │ │
|
||||
│ │ └─ 不存在 → 创建用户(nickName/avatarUrl 为空),返回用户数据
|
||||
│ │
|
||||
│ └─ 前端收到用户数据 → 写入内存 + Storage
|
||||
│
|
||||
└─ 完成,进入正常使用
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 二、技术细节
|
||||
|
||||
### 2.1 云函数:`userLogin`
|
||||
|
||||
**职责**:静默登录,upsert 用户记录。
|
||||
|
||||
```javascript
|
||||
// cloudfunctions/userLogin/index.js
|
||||
const cloud = require('wx-server-sdk');
|
||||
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
|
||||
|
||||
const db = cloud.database();
|
||||
|
||||
exports.main = async (event, context) => {
|
||||
const wxContext = cloud.getWXContext();
|
||||
const openid = wxContext.OPENID;
|
||||
const unionid = wxContext.UNIONID || null;
|
||||
|
||||
const usersCollection = db.collection('users');
|
||||
|
||||
// 查询是否已存在
|
||||
const { data } = await usersCollection.where({ openid }).limit(1).get();
|
||||
|
||||
const now = db.serverDate();
|
||||
|
||||
if (data.length > 0) {
|
||||
// 已存在:更新 lastActiveAt 和 unionid(如果有新值)
|
||||
const user = data[0];
|
||||
const updateData = { lastActiveAt: now };
|
||||
if (unionid && !user.unionid) {
|
||||
updateData.unionid = unionid;
|
||||
}
|
||||
await usersCollection.doc(user._id).update({ data: updateData });
|
||||
|
||||
return {
|
||||
code: 0,
|
||||
data: { ...user, ...updateData, lastActiveAt: new Date() },
|
||||
};
|
||||
} else {
|
||||
// 不存在:创建新用户
|
||||
const newUser = {
|
||||
openid,
|
||||
unionid,
|
||||
nickName: null,
|
||||
avatarUrl: null,
|
||||
totalDownloads: 0,
|
||||
createdAt: now,
|
||||
lastActiveAt: now,
|
||||
};
|
||||
const { _id } = await usersCollection.add({ data: newUser });
|
||||
|
||||
return {
|
||||
code: 0,
|
||||
data: {
|
||||
_id,
|
||||
...newUser,
|
||||
createdAt: new Date(),
|
||||
lastActiveAt: new Date(),
|
||||
},
|
||||
};
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
**要点**:
|
||||
|
||||
- `cloud.getWXContext()` 在云函数中自动获取调用者的 `OPENID`,无需前端传 code
|
||||
- `UNIONID` 仅在小程序绑定了开放平台且满足条件时才有值,所以设为可选
|
||||
- 使用 `db.serverDate()` 确保时间由服务端生成,避免客户端时间不准
|
||||
- `_id` 由云数据库自动生成(`add()` 时不指定),为随机唯一字符串;业务上通过 `openid` 唯一索引定位用户,`_id` 作为主键供子表(favorites、download_logs)的 `userId` 外键引用
|
||||
|
||||
---
|
||||
|
||||
### 2.2 前端登录逻辑
|
||||
|
||||
**位置**:建议封装为 `miniprogram/utils/auth.ts`
|
||||
|
||||
```typescript
|
||||
// miniprogram/utils/auth.ts
|
||||
|
||||
interface UserInfo {
|
||||
_id: string;
|
||||
openid: string;
|
||||
unionid: string | null;
|
||||
nickName: string | null;
|
||||
avatarUrl: string | null;
|
||||
totalDownloads: number;
|
||||
createdAt: string;
|
||||
lastActiveAt: string;
|
||||
}
|
||||
|
||||
const STORAGE_KEY = 'user_info';
|
||||
const STORAGE_EXPIRE_KEY = 'user_info_expire';
|
||||
const EXPIRE_DURATION = 7 * 24 * 60 * 60 * 1000; // 7 天
|
||||
|
||||
/** 内存中的用户数据(App 生命周期内有效) */
|
||||
let currentUser: UserInfo | null = null;
|
||||
|
||||
/**
|
||||
* 获取当前用户,优先内存 → Storage → 云函数登录
|
||||
*/
|
||||
export async function getUser(): Promise<UserInfo> {
|
||||
// 1. 内存中有,直接返回
|
||||
if (currentUser) return currentUser;
|
||||
|
||||
// 2. 尝试从 Storage 读取
|
||||
const cached = loadFromStorage();
|
||||
if (cached) {
|
||||
currentUser = cached;
|
||||
return cached;
|
||||
}
|
||||
|
||||
// 3. 静默登录
|
||||
return await silentLogin();
|
||||
}
|
||||
|
||||
/**
|
||||
* 静默登录:调用云函数
|
||||
*/
|
||||
async function silentLogin(): Promise<UserInfo> {
|
||||
const { result } = await wx.cloud.callFunction({
|
||||
name: 'userLogin',
|
||||
});
|
||||
|
||||
if (result.code !== 0) {
|
||||
throw new Error('登录失败');
|
||||
}
|
||||
|
||||
const user = result.data as UserInfo;
|
||||
currentUser = user;
|
||||
saveToStorage(user);
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Storage 读取用户数据(检查过期)
|
||||
*/
|
||||
function loadFromStorage(): UserInfo | null {
|
||||
try {
|
||||
const expire = wx.getStorageSync(STORAGE_EXPIRE_KEY);
|
||||
if (!expire || Date.now() > expire) {
|
||||
// 已过期,清除
|
||||
wx.removeStorageSync(STORAGE_KEY);
|
||||
wx.removeStorageSync(STORAGE_EXPIRE_KEY);
|
||||
return null;
|
||||
}
|
||||
const user = wx.getStorageSync(STORAGE_KEY);
|
||||
return user || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入 Storage
|
||||
*/
|
||||
function saveToStorage(user: UserInfo): void {
|
||||
try {
|
||||
wx.setStorageSync(STORAGE_KEY, user);
|
||||
wx.setStorageSync(STORAGE_EXPIRE_KEY, Date.now() + EXPIRE_DURATION);
|
||||
} catch {
|
||||
// Storage 写入失败不影响主流程
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除登录状态(用于退出登录或需要强制刷新时)
|
||||
*/
|
||||
export function clearUser(): void {
|
||||
currentUser = null;
|
||||
wx.removeStorageSync(STORAGE_KEY);
|
||||
wx.removeStorageSync(STORAGE_EXPIRE_KEY);
|
||||
}
|
||||
|
||||
/**
|
||||
* 强制刷新用户数据(跳过缓存)
|
||||
*/
|
||||
export async function refreshUser(): Promise<UserInfo> {
|
||||
clearUser();
|
||||
return await silentLogin();
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.3 调用时机
|
||||
|
||||
在 `app.ts` 的 `onLaunch` 中触发登录:
|
||||
|
||||
```typescript
|
||||
// app.ts
|
||||
import { getUser } from './utils/auth';
|
||||
|
||||
App({
|
||||
onLaunch() {
|
||||
// 初始化云开发
|
||||
wx.cloud.init({ env: 'your-env-id' });
|
||||
|
||||
// 静默登录(不阻塞页面渲染)
|
||||
getUser().catch((err) => {
|
||||
console.error('静默登录失败', err);
|
||||
});
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
**注意**:登录是异步的,不阻塞页面渲染。页面中需要用户数据时通过 `await getUser()` 获取,如果登录已完成会立即返回内存数据。
|
||||
|
||||
---
|
||||
|
||||
### 2.4 缓存过期策略
|
||||
|
||||
| 策略 | 说明 |
|
||||
| ---------- | ----------------------------------------- |
|
||||
| 有效期 | 7 天 |
|
||||
| 过期后行为 | 下次 `getUser()` 时自动触发静默登录 |
|
||||
| 过期目的 | 定期刷新 `lastActiveAt`,保持活跃数据准确 |
|
||||
| 强制刷新 | 调用 `refreshUser()` 可随时强制重新登录 |
|
||||
|
||||
---
|
||||
|
||||
## 三、昵称与头像授权(后续实现)
|
||||
|
||||
静默登录不获取用户昵称和头像。当需要展示或使用这些信息时(如个人中心页),引导用户主动填写:
|
||||
|
||||
```typescript
|
||||
// 使用微信头像昵称填写能力(基础库 2.21.2+)
|
||||
// 在 wxml 中使用 <button open-type="chooseAvatar"> 获取头像
|
||||
// 使用 <input type="nickname"> 获取昵称
|
||||
|
||||
export async function updateProfile(
|
||||
nickName: string,
|
||||
avatarUrl: string,
|
||||
): Promise<void> {
|
||||
const { result } = await wx.cloud.callFunction({
|
||||
name: 'userLogin',
|
||||
data: {
|
||||
action: 'updateProfile',
|
||||
nickName,
|
||||
avatarUrl,
|
||||
},
|
||||
});
|
||||
|
||||
if (result.code === 0) {
|
||||
// 更新本地缓存
|
||||
const user = await getUser();
|
||||
user.nickName = nickName;
|
||||
user.avatarUrl = avatarUrl;
|
||||
saveToStorage(user);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> 注:微信已废弃 `wx.getUserProfile` 和 `wx.getUserInfo` 获取真实用户信息的能力,现在只能通过头像昵称填写组件让用户主动填写。
|
||||
|
||||
---
|
||||
|
||||
## 四、云函数目录结构
|
||||
|
||||
```
|
||||
cloudfunctions/
|
||||
└── userLogin/
|
||||
├── index.js ← 入口,支持 action 路由
|
||||
├── package.json
|
||||
└── config.json ← 云函数配置
|
||||
```
|
||||
|
||||
若后续 `updateProfile` 等操作较多,可在同一个云函数内通过 `event.action` 路由:
|
||||
|
||||
```javascript
|
||||
exports.main = async (event, context) => {
|
||||
const { action } = event;
|
||||
|
||||
switch (action) {
|
||||
case 'updateProfile':
|
||||
return await handleUpdateProfile(event, context);
|
||||
default:
|
||||
return await handleSilentLogin(event, context);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 五、安全考虑
|
||||
|
||||
| 项目 | 措施 |
|
||||
| ------------ | --------------------------------------------------------- |
|
||||
| openid 来源 | 仅从 `cloud.getWXContext()` 获取,不信任前端传入 |
|
||||
| unionid | 服务端获取,不暴露给前端 |
|
||||
| Storage 数据 | 不存储敏感信息(openid 不算高敏感,但也不主动展示给用户) |
|
||||
| 接口幂等 | upsert 逻辑天然幂等,重复调用不会创建多条记录 |
|
||||
|
||||
---
|
||||
|
||||
## 六、与现有架构的关系
|
||||
|
||||
- **数据库**:使用 `users` 集合,字段设计见 [小程序云开发方案和数据库设计.md](./小程序云开发方案和数据库设计.md) §3.5
|
||||
- **其他云函数**:需要用户身份的云函数(如收藏、下载记录)通过 `cloud.getWXContext().OPENID` 查询 `users` 集合获取 `_id`,作为 `userId` 关联
|
||||
- **前端**:各页面通过 `getUser()` 获取用户数据,无需关心登录细节
|
||||
@@ -1,4 +1,5 @@
|
||||
import { defaultPrintConfig } from './config/config';
|
||||
import { getUser } from './utils/auth';
|
||||
import { generateUUID, getAppUUID, setAppUUID } from './utils/uuid';
|
||||
|
||||
const STORAGE_KEY_PAGE_CONFIG = 'pageConfig';
|
||||
@@ -39,6 +40,11 @@ App<IAppOption>({
|
||||
this.globalData.printConfig = printConfig;
|
||||
}
|
||||
|
||||
// 静默登录(不阻塞页面渲染)
|
||||
getUser().catch((err) => {
|
||||
console.error('静默登录失败', err);
|
||||
});
|
||||
|
||||
void this.loadPageConfig();
|
||||
},
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
} from '../shared/data/fontProfiles';
|
||||
import { loadLetterFont } from '../shared/draw/drawTools';
|
||||
import type { DebugPublishMeta } from '../../utils/debugPublish';
|
||||
import { incrementWorksheetLikes } from '../../utils/worksheetStats';
|
||||
import { addFavorite, removeFavorite, batchCheckFavorited } from '../../utils/favorites';
|
||||
|
||||
/** 三字母精练分组:26 字母每 3 个一组 */
|
||||
const TRIPLE_GROUPS: { title: string; letters: string[] }[] = [];
|
||||
@@ -82,6 +82,7 @@ createPage(
|
||||
boxWidth: 0,
|
||||
drawService: null as LetterTracingDraw | null,
|
||||
fontProfile: DEFAULT_LETTER_PROFILE as FontProfile,
|
||||
_favoritedMap: {} as Record<string, boolean>,
|
||||
|
||||
data: {
|
||||
pageTitle: '字母描红',
|
||||
@@ -147,6 +148,8 @@ createPage(
|
||||
updates as Partial<PageData> & WechatMiniprogram.IAnyObject,
|
||||
);
|
||||
}
|
||||
|
||||
this.loadFavoritedMap();
|
||||
},
|
||||
|
||||
/** 用户点击模式选择器时切换 worksheet */
|
||||
@@ -275,8 +278,14 @@ createPage(
|
||||
async onPreviewFavorite() {
|
||||
const next = !this.data.isPreviewFavorite;
|
||||
this.setData({ isPreviewFavorite: next });
|
||||
const id = this.data.worksheetId;
|
||||
if (id) {
|
||||
this._favoritedMap[id] = next;
|
||||
if (next) {
|
||||
incrementWorksheetLikes(this.data.worksheetId);
|
||||
addFavorite(id);
|
||||
} else {
|
||||
removeFavorite(id);
|
||||
}
|
||||
}
|
||||
wx.showToast({
|
||||
title: next ? '收藏成功' : '已取消收藏',
|
||||
@@ -284,6 +293,15 @@ createPage(
|
||||
});
|
||||
},
|
||||
|
||||
async loadFavoritedMap() {
|
||||
const ids = LETTER_TRACING_MODE_OPTIONS.map((d) => d.id);
|
||||
this._favoritedMap = await batchCheckFavorited(ids);
|
||||
const currentId = this.data.worksheetId;
|
||||
if (this._favoritedMap[currentId]) {
|
||||
this.setData({ isPreviewFavorite: true });
|
||||
}
|
||||
},
|
||||
|
||||
getPublishMeta(): DebugPublishMeta {
|
||||
const meta = getPublishMetaByMode(this.data.worksheetId);
|
||||
if (!meta) {
|
||||
@@ -358,7 +376,7 @@ createPage(
|
||||
worksheetId,
|
||||
functionId: worksheetId,
|
||||
traceMode,
|
||||
isPreviewFavorite: false,
|
||||
isPreviewFavorite: !!this._favoritedMap[worksheetId],
|
||||
selectedLetter,
|
||||
selectedLetterPair: `${selectedLetter}${selectedLetter.toLowerCase()}`,
|
||||
letterCaseLower,
|
||||
|
||||
@@ -6,9 +6,9 @@ import {
|
||||
type FocusTypeConfig,
|
||||
type FocusTypeAction,
|
||||
} from './registry';
|
||||
import { getPublishMetaByFocusState } from './focusDraw.config';
|
||||
import { getPublishMetaByFocusState, FOCUS_WORKSHEET_DEFINITIONS } from './focusDraw.config';
|
||||
import type { DebugPublishMeta } from '../../utils/debugPublish';
|
||||
import { incrementWorksheetLikes } from '../../utils/worksheetStats';
|
||||
import { addFavorite, removeFavorite, batchCheckFavorited } from '../../utils/favorites';
|
||||
|
||||
const TYPE_LIST = FOCUS_TYPE_CONFIGS.map((t) => ({
|
||||
id: t.id,
|
||||
@@ -24,6 +24,7 @@ createFocusPage({
|
||||
drawService: null as BaseDrawService | null,
|
||||
currentTypeConfig: null as FocusTypeConfig | null,
|
||||
currentData: null as any,
|
||||
_favoritedMap: {} as Record<string, boolean>,
|
||||
|
||||
data: {
|
||||
pageTitle: '专注力练习',
|
||||
@@ -73,6 +74,8 @@ createFocusPage({
|
||||
});
|
||||
|
||||
this.initPageInfo(routeId, title);
|
||||
|
||||
this.loadFavoritedMap();
|
||||
},
|
||||
|
||||
onCanvasReady(e: WechatMiniprogram.CustomEvent) {
|
||||
@@ -121,7 +124,9 @@ createFocusPage({
|
||||
selectedTypeId: id,
|
||||
functionId: id,
|
||||
pageTitle: title,
|
||||
isPreviewFavorite: false,
|
||||
isPreviewFavorite: !!this._favoritedMap[
|
||||
getPublishMetaByFocusState(id, id, mode)?.id || id
|
||||
],
|
||||
showActions: !!typeConfig.actions,
|
||||
currentActions: typeConfig.actions || [],
|
||||
actionsTitle: typeConfig.actionsTitle || '选择模式',
|
||||
@@ -158,7 +163,7 @@ createFocusPage({
|
||||
this.setData({
|
||||
currentMode: value,
|
||||
pageTitle: title,
|
||||
isPreviewFavorite: false,
|
||||
isPreviewFavorite: !!this._favoritedMap[this.getWorksheetStatsIdFor(value)],
|
||||
});
|
||||
|
||||
this.initPageInfo(this.data.functionId, title);
|
||||
@@ -202,9 +207,14 @@ createFocusPage({
|
||||
async onPreviewFavorite() {
|
||||
const next = !this.data.isPreviewFavorite;
|
||||
this.setData({ isPreviewFavorite: next });
|
||||
if (next) {
|
||||
const id = this.getWorksheetStatsId();
|
||||
if (id) incrementWorksheetLikes(id);
|
||||
if (id) {
|
||||
this._favoritedMap[id] = next;
|
||||
if (next) {
|
||||
addFavorite(id);
|
||||
} else {
|
||||
removeFavorite(id);
|
||||
}
|
||||
}
|
||||
wx.showToast({
|
||||
title: next ? '收藏成功' : '已取消收藏',
|
||||
@@ -221,6 +231,24 @@ createFocusPage({
|
||||
return meta?.id || this.data.functionId;
|
||||
},
|
||||
|
||||
getWorksheetStatsIdFor(mode: string): string {
|
||||
const meta = getPublishMetaByFocusState(
|
||||
this.data.functionId,
|
||||
this.data.selectedTypeId,
|
||||
mode,
|
||||
);
|
||||
return meta?.id || this.data.functionId;
|
||||
},
|
||||
|
||||
async loadFavoritedMap() {
|
||||
const ids = FOCUS_WORKSHEET_DEFINITIONS.map((d) => d.id);
|
||||
this._favoritedMap = await batchCheckFavorited(ids);
|
||||
const currentId = this.getWorksheetStatsId();
|
||||
if (this._favoritedMap[currentId]) {
|
||||
this.setData({ isPreviewFavorite: true });
|
||||
}
|
||||
},
|
||||
|
||||
getPublishMeta(): DebugPublishMeta {
|
||||
const meta = getPublishMetaByFocusState(
|
||||
this.data.functionId,
|
||||
|
||||
@@ -6,9 +6,9 @@ import {
|
||||
type MathTypeConfig,
|
||||
type MathTypeAction,
|
||||
} from './registry';
|
||||
import { getPublishMetaByMathState } from './mathDraw.config';
|
||||
import { getPublishMetaByMathState, MATH_WORKSHEET_DEFINITIONS } from './mathDraw.config';
|
||||
import type { DebugPublishMeta } from '../../utils/debugPublish';
|
||||
import { incrementWorksheetLikes } from '../../utils/worksheetStats';
|
||||
import { addFavorite, removeFavorite, batchCheckFavorited } from '../../utils/favorites';
|
||||
|
||||
const TYPE_LIST = MATH_TYPE_CONFIGS.map((t) => ({
|
||||
id: t.id,
|
||||
@@ -25,6 +25,7 @@ createMathPage({
|
||||
currentTypeConfig: null as MathTypeConfig | null,
|
||||
currentData: null as any,
|
||||
routeExtra: null as Record<string, any> | null,
|
||||
_favoritedMap: {} as Record<string, boolean>,
|
||||
|
||||
data: {
|
||||
pageTitle: '数学练习',
|
||||
@@ -82,6 +83,9 @@ createMathPage({
|
||||
});
|
||||
|
||||
this.initPageInfo(routeId, title);
|
||||
|
||||
// 加载收藏状态
|
||||
this.loadFavoritedMap();
|
||||
},
|
||||
|
||||
onCanvasReady(e: WechatMiniprogram.CustomEvent) {
|
||||
@@ -131,7 +135,9 @@ createMathPage({
|
||||
selectedTypeId: id,
|
||||
functionId: id,
|
||||
pageTitle: title,
|
||||
isPreviewFavorite: false,
|
||||
isPreviewFavorite: !!this._favoritedMap[
|
||||
getPublishMetaByMathState(id, id, mode)?.id || id
|
||||
],
|
||||
showActions: !!typeConfig.actions,
|
||||
currentActions: typeConfig.actions || [],
|
||||
actionsTitle: typeConfig.actionsTitle || '选择模式',
|
||||
@@ -172,7 +178,7 @@ createMathPage({
|
||||
this.setData({
|
||||
currentMode: value,
|
||||
pageTitle: title,
|
||||
isPreviewFavorite: false,
|
||||
isPreviewFavorite: !!this._favoritedMap[this.getWorksheetStatsIdFor(value)],
|
||||
});
|
||||
|
||||
this.initPageInfo(this.data.functionId, title);
|
||||
@@ -266,9 +272,14 @@ createMathPage({
|
||||
async onPreviewFavorite() {
|
||||
const next = !this.data.isPreviewFavorite;
|
||||
this.setData({ isPreviewFavorite: next });
|
||||
if (next) {
|
||||
const id = this.getWorksheetStatsId();
|
||||
if (id) incrementWorksheetLikes(id);
|
||||
if (id) {
|
||||
this._favoritedMap[id] = next;
|
||||
if (next) {
|
||||
addFavorite(id);
|
||||
} else {
|
||||
removeFavorite(id);
|
||||
}
|
||||
}
|
||||
wx.showToast({
|
||||
title: next ? '收藏成功' : '已取消收藏',
|
||||
@@ -285,6 +296,25 @@ createMathPage({
|
||||
return meta?.id || this.data.functionId;
|
||||
},
|
||||
|
||||
getWorksheetStatsIdFor(mode: string): string {
|
||||
const meta = getPublishMetaByMathState(
|
||||
this.data.functionId,
|
||||
this.data.selectedTypeId,
|
||||
mode,
|
||||
);
|
||||
return meta?.id || this.data.functionId;
|
||||
},
|
||||
|
||||
async loadFavoritedMap() {
|
||||
const ids = MATH_WORKSHEET_DEFINITIONS.map((d) => d.id);
|
||||
this._favoritedMap = await batchCheckFavorited(ids);
|
||||
// 回显当前选中的收藏状态
|
||||
const currentId = this.getWorksheetStatsId();
|
||||
if (this._favoritedMap[currentId]) {
|
||||
this.setData({ isPreviewFavorite: true });
|
||||
}
|
||||
},
|
||||
|
||||
getPublishMeta(): DebugPublishMeta {
|
||||
const meta = getPublishMetaByMathState(
|
||||
this.data.functionId,
|
||||
|
||||
@@ -1,26 +1,23 @@
|
||||
import { NAV_INNER_PX } from '../../utils/navMetrics';
|
||||
import { getFavoriteList, removeFavorite } from '../../utils/favorites';
|
||||
import { getDownloadLogs } from '../../utils/downloadLogs';
|
||||
import type { FavoriteRecord } from '../../utils/favorites';
|
||||
import type { DownloadLogRecord } from '../../utils/downloadLogs';
|
||||
|
||||
const { statusBarHeight } = wx.getWindowInfo();
|
||||
const NAV_BLOCK_HEIGHT = statusBarHeight + NAV_INNER_PX;
|
||||
|
||||
type FavoritesTab = 'favorites' | 'downloads';
|
||||
|
||||
type FavoriteItem =
|
||||
| {
|
||||
type FavoriteItem = {
|
||||
id: string;
|
||||
worksheetId: string;
|
||||
variant: 'standard';
|
||||
title: string;
|
||||
metaLine: string;
|
||||
stars: number;
|
||||
timeBadge: string;
|
||||
thumb: string;
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
variant: 'featured';
|
||||
title: string;
|
||||
metaLine: string;
|
||||
tags: string[];
|
||||
};
|
||||
|
||||
type DownloadRow = {
|
||||
@@ -39,88 +36,94 @@ type DownloadSection = {
|
||||
items: DownloadRow[];
|
||||
};
|
||||
|
||||
const MOCK_FAVORITES: FavoriteItem[] = [
|
||||
{
|
||||
id: '1',
|
||||
variant: 'standard',
|
||||
title: '10以内加法',
|
||||
metaLine: '数学启蒙 · 4-6岁 · ',
|
||||
stars: 2,
|
||||
timeBadge: '收藏于 3 天前',
|
||||
thumb: 'https://lh3.googleusercontent.com/aida-public/AB6AXuD7khp0rJABfa9yFrMt9ZgIhAPyN44XmJ2pXNBgCzbgBvwA5ptFZVty013JedVzbE9_VvCQnToN7QETLDKjtiX22igzK-a5h4E8wjKrembFW4eVuk1RsJIbHjx3_cCz0hJ7_t76hF8t-Qdod_5R9sNMor1ZEjf6dGNp6UI_eIBjsN9b22iCTJ2VB-IEh0Rmil6_iC4Og-4I03IcQDV2rTHYIXcZxjiay1IiYGXw3wJ3bfo2SF2N7ZFT00akTgYU-9JyF7xJ6n15Yzc',
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
variant: 'standard',
|
||||
title: '图形连连看',
|
||||
metaLine: '逻辑思维 · 3-5岁 · ',
|
||||
stars: 1,
|
||||
timeBadge: '收藏于 5 天前',
|
||||
thumb: 'https://lh3.googleusercontent.com/aida-public/AB6AXuBY_0Rr153ZBT4IHcMyFtrcgl-y2ZRyVnOuGecnn7f4PZKoAx2lOuCorsMmfRa72s0JmbXrt4XT3QU1x7cIbZUyhv_EXwCfMaNxtkHc-ymIBIQ5jqm5oiQebrEWH4kjv14JdkCiziT4xzac4TdVN5yqpk7Wlg80QBl_ldDmAQqIgcUeN2PvlVvhmpOYmFeWE2HS3I_e4vV1J8s_cfV9_4g7y8SbxlSfnTmgQNeXrVbcdwaNEAGQWp92Iif0d2pVIqdfuUHO1pTw8oQ',
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
variant: 'standard',
|
||||
title: '拼音字母认读',
|
||||
metaLine: '语文基础 · 5-7岁 · ',
|
||||
stars: 3,
|
||||
timeBadge: '收藏于 1 周前',
|
||||
thumb: 'https://lh3.googleusercontent.com/aida-public/AB6AXuC54mXQ8620XwIsWmUHBHJGdmpF8uE4cSYxwR2NLJTsa6gYdTCHz2tqrKbGOye-y0CGgCPPWwJXzEuB2ZYrQ3CWWPlamvbjhTUDYf8yoA9Lyapll1t2w17AqzSHrbBPNFrq931IUCis64b51kslQZoq3c0KslZsBQiky-YSnuE7xUuNsgiF4hOak_ReFFufWE53h1sPkjHFeRM-H34b-e1MCNxGObGPhI0mNlJ_qz0c8aCuS-jdnDocSvIYda-iVcJLWcIT-mO6klw',
|
||||
},
|
||||
{
|
||||
id: '4',
|
||||
variant: 'featured',
|
||||
title: '趣味英语单词卡',
|
||||
metaLine: '语言学习 · 4-8岁 · ⭐⭐⭐',
|
||||
tags: ['畅销经典', '全彩打印'],
|
||||
},
|
||||
];
|
||||
function mapFavoriteToItem(record: FavoriteRecord): FavoriteItem {
|
||||
const ws = record.worksheet;
|
||||
const title = ws?.title || '未知题型';
|
||||
const category = ws?.category || '';
|
||||
const ageRange = ws ? `${ws.ageMin}-${ws.ageMax}岁` : '';
|
||||
const metaLine = [category, ageRange].filter(Boolean).join(' · ') + ' · ';
|
||||
const difficulty = ws?.difficulty || 0;
|
||||
const timeBadge = formatTimeBadge(record.createdAt);
|
||||
|
||||
const MOCK_DOWNLOADS: DownloadSection[] = [
|
||||
{
|
||||
key: 'today',
|
||||
label: '今天',
|
||||
items: [
|
||||
{
|
||||
id: 'd1',
|
||||
title: '拼音描红 · 声母表',
|
||||
time: '14:32',
|
||||
return {
|
||||
id: record._id,
|
||||
worksheetId: record.worksheetId,
|
||||
variant: 'standard',
|
||||
title,
|
||||
metaLine,
|
||||
stars: Math.min(difficulty, 3),
|
||||
timeBadge,
|
||||
thumb: ws?.previewImg || '',
|
||||
};
|
||||
}
|
||||
|
||||
function formatTimeBadge(dateStr: string): string {
|
||||
const date = new Date(dateStr);
|
||||
const now = new Date();
|
||||
const diff = now.getTime() - date.getTime();
|
||||
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
|
||||
|
||||
if (days === 0) return '收藏于今天';
|
||||
if (days === 1) return '收藏于昨天';
|
||||
if (days < 7) return `收藏于 ${days} 天前`;
|
||||
if (days < 30) return `收藏于 ${Math.floor(days / 7)} 周前`;
|
||||
return `收藏于 ${Math.floor(days / 30)} 个月前`;
|
||||
}
|
||||
|
||||
function groupDownloadsByDate(records: DownloadLogRecord[]): DownloadSection[] {
|
||||
const now = new Date();
|
||||
const todayStr = formatDateKey(now);
|
||||
const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
||||
const yesterdayStr = formatDateKey(yesterday);
|
||||
|
||||
const groups: Record<string, { label: string; items: DownloadRow[] }> = {};
|
||||
|
||||
for (const record of records) {
|
||||
const date = new Date(record.createdAt);
|
||||
const key = formatDateKey(date);
|
||||
let label: string;
|
||||
|
||||
if (key === todayStr) {
|
||||
label = '今天';
|
||||
} else if (key === yesterdayStr) {
|
||||
label = '昨天';
|
||||
} else {
|
||||
label = `${date.getMonth() + 1}月${date.getDate()}日`;
|
||||
}
|
||||
|
||||
if (!groups[key]) {
|
||||
groups[key] = { label, items: [] };
|
||||
}
|
||||
|
||||
const ws = record.worksheet;
|
||||
groups[key].items.push({
|
||||
id: record._id,
|
||||
title: ws?.title || '未知题型',
|
||||
time: `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`,
|
||||
status: '已保存相册',
|
||||
statusHighlight: true,
|
||||
thumb: 'https://lh3.googleusercontent.com/aida-public/AB6AXuBCm6X4rhibw2_WxP-U0dDyOsiYol3y12OnEXHRkPONZYMQBUcr3Grqo1IbwH3sdWPg5jIUeIbr_AEwv_hFwUOMMz9jTIIMc6Pke1bzSvlQcgdDq-zMEIU4A--IQFX59ac-8BscCajXZcd4v8rE6JEZFf1-aztKclPTkE_Rrgj-nbVCy5V6bOE6yDOB67VdTbcqiOdaFN18ju_MgWVo3FQZLwIUZOBahkPl0vDIKA0mkiaGK9eiFpfnERYxkYG3eWJZ40umTYp46Jo',
|
||||
},
|
||||
{
|
||||
id: 'd2',
|
||||
title: '趣味口算题卡',
|
||||
time: '09:15',
|
||||
status: '已下载 PDF',
|
||||
statusHighlight: false,
|
||||
thumb: 'https://lh3.googleusercontent.com/aida-public/AB6AXuBxNORxN_vftYMLaMjZVscL-o9bZnBrfUi7IAqOrFATIztGV12_0ggwgae-fmk0cORWtysZWJJDcAzj0NEyniFxbREoGDuq9U4kytprJkA70_k0MCzPgStmq0bRwu1Gx1j4peglFam8PH6IlPvOMbiHQ7-fMFfYTSBtA1p7Dp06NDOzS2VrMlF8VxjEgihVmhHUrHePVvXlktUkXBKNzrXEXrogO3iOyouTUKyvJh0TeChKUv3KohMoD5ol7C3fjBhdHf7QD4StOQ4',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'yesterday',
|
||||
label: '昨天',
|
||||
items: [
|
||||
{
|
||||
id: 'd3',
|
||||
title: '汉字笔画基础训练',
|
||||
time: '16:40',
|
||||
status: '已发送邮件',
|
||||
statusHighlight: false,
|
||||
placeholder: 'draw',
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
thumb: ws?.previewImg,
|
||||
});
|
||||
}
|
||||
|
||||
return Object.keys(groups).map((key) => ({
|
||||
key,
|
||||
label: groups[key].label,
|
||||
items: groups[key].items,
|
||||
}));
|
||||
}
|
||||
|
||||
function formatDateKey(date: Date): string {
|
||||
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
|
||||
}
|
||||
|
||||
Page({
|
||||
data: {
|
||||
favScrollHeight: 0,
|
||||
activeTab: 'favorites' as FavoritesTab,
|
||||
favoriteList: MOCK_FAVORITES as FavoriteItem[],
|
||||
downloadSections: MOCK_DOWNLOADS as DownloadSection[],
|
||||
favoriteList: [] as FavoriteItem[],
|
||||
downloadSections: [] as DownloadSection[],
|
||||
loading: false,
|
||||
},
|
||||
|
||||
onLoad() {
|
||||
@@ -136,6 +139,7 @@ Page({
|
||||
this.setData({ activeTab: tab });
|
||||
wx.removeStorageSync('favorites_active_tab');
|
||||
}
|
||||
this.loadData();
|
||||
},
|
||||
|
||||
onTabSwitch(e: WechatMiniprogram.TouchEvent) {
|
||||
@@ -144,6 +148,24 @@ Page({
|
||||
this.setData({ activeTab: tab });
|
||||
},
|
||||
|
||||
async loadData() {
|
||||
this.setData({ loading: true });
|
||||
await Promise.all([this.loadFavorites(), this.loadDownloads()]);
|
||||
this.setData({ loading: false });
|
||||
},
|
||||
|
||||
async loadFavorites() {
|
||||
const records = await getFavoriteList();
|
||||
const list = records.map((r) => mapFavoriteToItem(r));
|
||||
this.setData({ favoriteList: list });
|
||||
},
|
||||
|
||||
async loadDownloads() {
|
||||
const records = await getDownloadLogs();
|
||||
const sections = groupDownloadsByDate(records);
|
||||
this.setData({ downloadSections: sections });
|
||||
},
|
||||
|
||||
onDiscoverTap() {
|
||||
wx.switchTab({ url: '/pages/home/home' });
|
||||
},
|
||||
@@ -152,12 +174,24 @@ Page({
|
||||
wx.showToast({ title: '搜索功能开发中', icon: 'none' });
|
||||
},
|
||||
|
||||
onRemoveFavorite(e: WechatMiniprogram.TouchEvent) {
|
||||
async onRemoveFavorite(e: WechatMiniprogram.TouchEvent) {
|
||||
const id = e.currentTarget.dataset.id as string | undefined;
|
||||
if (!id) return;
|
||||
const list = (this.data.favoriteList as FavoriteItem[]).filter((item) => item.id !== id);
|
||||
|
||||
const item = (this.data.favoriteList as FavoriteItem[]).find(
|
||||
(i) => i.id === id,
|
||||
);
|
||||
if (!item) return;
|
||||
|
||||
// 乐观更新 UI
|
||||
const list = (this.data.favoriteList as FavoriteItem[]).filter(
|
||||
(i) => i.id !== id,
|
||||
);
|
||||
this.setData({ favoriteList: list });
|
||||
wx.showToast({ title: '已取消收藏', icon: 'none' });
|
||||
|
||||
// 调用云端
|
||||
await removeFavorite(item.worksheetId);
|
||||
},
|
||||
|
||||
onClearHistory() {
|
||||
@@ -174,6 +208,9 @@ Page({
|
||||
|
||||
onDownloadMore(e: WechatMiniprogram.TouchEvent) {
|
||||
const id = e.currentTarget.dataset.id as string | undefined;
|
||||
wx.showToast({ title: id ? `更多操作:${id}` : '更多', icon: 'none' });
|
||||
wx.showToast({
|
||||
title: id ? `更多操作:${id}` : '更多',
|
||||
icon: 'none',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
interface UserInfo {
|
||||
_id: string;
|
||||
openid: string;
|
||||
unionid: string | null;
|
||||
nickName: string | null;
|
||||
avatarUrl: string | null;
|
||||
totalDownloads: number;
|
||||
createdAt: string;
|
||||
lastActiveAt: string;
|
||||
}
|
||||
|
||||
const STORAGE_KEY = 'user_info';
|
||||
const STORAGE_EXPIRE_KEY = 'user_info_expire';
|
||||
const EXPIRE_DURATION = 7 * 24 * 60 * 60 * 1000; // 7 天
|
||||
|
||||
/** 内存中的用户数据(App 生命周期内有效) */
|
||||
let currentUser: UserInfo | null = null;
|
||||
|
||||
/** 登录进行中的 Promise(防止并发重复调用) */
|
||||
let loginPromise: Promise<UserInfo> | null = null;
|
||||
|
||||
/**
|
||||
* 获取当前用户,优先内存 → Storage → 云函数登录
|
||||
*/
|
||||
export async function getUser(): Promise<UserInfo> {
|
||||
// 1. 内存中有,直接返回
|
||||
if (currentUser) return currentUser;
|
||||
|
||||
// 2. 尝试从 Storage 读取
|
||||
const cached = loadFromStorage();
|
||||
if (cached) {
|
||||
currentUser = cached;
|
||||
return cached;
|
||||
}
|
||||
|
||||
// 3. 静默登录(防止并发)
|
||||
if (!loginPromise) {
|
||||
loginPromise = silentLogin().finally(() => {
|
||||
loginPromise = null;
|
||||
});
|
||||
}
|
||||
return loginPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* 静默登录:调用云函数
|
||||
*/
|
||||
async function silentLogin(): Promise<UserInfo> {
|
||||
const res = await wx.cloud.callFunction({
|
||||
name: 'userLogin',
|
||||
});
|
||||
const result = (res?.result as any) || {};
|
||||
|
||||
if (result.code !== 0) {
|
||||
throw new Error('登录失败');
|
||||
}
|
||||
|
||||
const user = result.data as UserInfo;
|
||||
currentUser = user;
|
||||
saveToStorage(user);
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Storage 读取用户数据(检查过期)
|
||||
*/
|
||||
function loadFromStorage(): UserInfo | null {
|
||||
try {
|
||||
const expire = wx.getStorageSync(STORAGE_EXPIRE_KEY);
|
||||
if (!expire || Date.now() > expire) {
|
||||
wx.removeStorageSync(STORAGE_KEY);
|
||||
wx.removeStorageSync(STORAGE_EXPIRE_KEY);
|
||||
return null;
|
||||
}
|
||||
const user = wx.getStorageSync(STORAGE_KEY);
|
||||
return user || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入 Storage
|
||||
*/
|
||||
function saveToStorage(user: UserInfo): void {
|
||||
try {
|
||||
wx.setStorageSync(STORAGE_KEY, user);
|
||||
wx.setStorageSync(STORAGE_EXPIRE_KEY, Date.now() + EXPIRE_DURATION);
|
||||
} catch {
|
||||
// Storage 写入失败不影响主流程
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除登录状态
|
||||
*/
|
||||
export function clearUser(): void {
|
||||
currentUser = null;
|
||||
wx.removeStorageSync(STORAGE_KEY);
|
||||
wx.removeStorageSync(STORAGE_EXPIRE_KEY);
|
||||
}
|
||||
|
||||
/**
|
||||
* 强制刷新用户数据(跳过缓存)
|
||||
*/
|
||||
export async function refreshUser(): Promise<UserInfo> {
|
||||
clearUser();
|
||||
return await silentLogin();
|
||||
}
|
||||
|
||||
export type { UserInfo };
|
||||
@@ -0,0 +1,56 @@
|
||||
import { getUser } from './auth';
|
||||
|
||||
export interface DownloadLogRecord {
|
||||
_id: string;
|
||||
userId: string;
|
||||
worksheetId: string;
|
||||
createdAt: string;
|
||||
worksheet?: {
|
||||
_id: string;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
category: string;
|
||||
subcategory: string;
|
||||
previewImg: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录下载日志
|
||||
*/
|
||||
export async function addDownloadLog(worksheetId: string): Promise<boolean> {
|
||||
if (!worksheetId) return false;
|
||||
try {
|
||||
await getUser();
|
||||
const res = await wx.cloud.callFunction({
|
||||
name: 'userDownloadLogs',
|
||||
data: { action: 'add', worksheetId },
|
||||
});
|
||||
const result = (res?.result as any) || {};
|
||||
return result.code === 0;
|
||||
} catch (e) {
|
||||
console.error('addDownloadLog failed', e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取下载历史
|
||||
*/
|
||||
export async function getDownloadLogs(
|
||||
page = 1,
|
||||
pageSize = 20,
|
||||
): Promise<DownloadLogRecord[]> {
|
||||
try {
|
||||
await getUser();
|
||||
const res = await wx.cloud.callFunction({
|
||||
name: 'userDownloadLogs',
|
||||
data: { action: 'list', page, pageSize },
|
||||
});
|
||||
const result = (res?.result as any) || {};
|
||||
return result.code === 0 ? result.data : [];
|
||||
} catch (e) {
|
||||
console.error('getDownloadLogs failed', e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
import { checkAndSaveImage } from './saveImage';
|
||||
import tracker from './tracker';
|
||||
import { incrementWorksheetDownloads } from './worksheetStats';
|
||||
import { addDownloadLog } from './downloadLogs';
|
||||
|
||||
// 存储键名
|
||||
const STORAGE_KEY_DOWNLOAD_COUNT = 'downloadCount';
|
||||
@@ -212,7 +212,7 @@ function doDownload(
|
||||
if (saved) {
|
||||
incrementDownloadCount();
|
||||
if (options.worksheetId) {
|
||||
incrementWorksheetDownloads(options.worksheetId);
|
||||
addDownloadLog(options.worksheetId);
|
||||
}
|
||||
}
|
||||
return saved;
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import { getUser } from './auth';
|
||||
|
||||
export interface FavoriteRecord {
|
||||
_id: string;
|
||||
userId: string;
|
||||
worksheetId: string;
|
||||
createdAt: string;
|
||||
worksheet?: {
|
||||
_id: string;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
category: string;
|
||||
subcategory: string;
|
||||
ageMin: number;
|
||||
ageMax: number;
|
||||
difficulty: number;
|
||||
previewImg: string;
|
||||
tags: string[];
|
||||
} | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加收藏
|
||||
*/
|
||||
export async function addFavorite(worksheetId: string): Promise<boolean> {
|
||||
try {
|
||||
await getUser(); // 确保已登录
|
||||
const res = await wx.cloud.callFunction({
|
||||
name: 'userFavorites',
|
||||
data: { action: 'add', worksheetId },
|
||||
});
|
||||
const result = (res?.result as any) || {};
|
||||
return result.code === 0;
|
||||
} catch (e) {
|
||||
console.error('addFavorite failed', e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消收藏
|
||||
*/
|
||||
export async function removeFavorite(worksheetId: string): Promise<boolean> {
|
||||
try {
|
||||
await getUser();
|
||||
const res = await wx.cloud.callFunction({
|
||||
name: 'userFavorites',
|
||||
data: { action: 'remove', worksheetId },
|
||||
});
|
||||
const result = (res?.result as any) || {};
|
||||
return result.code === 0;
|
||||
} catch (e) {
|
||||
console.error('removeFavorite failed', e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取收藏列表
|
||||
*/
|
||||
export async function getFavoriteList(
|
||||
page = 1,
|
||||
pageSize = 20,
|
||||
): Promise<FavoriteRecord[]> {
|
||||
try {
|
||||
await getUser();
|
||||
const res = await wx.cloud.callFunction({
|
||||
name: 'userFavorites',
|
||||
data: { action: 'list', page, pageSize },
|
||||
});
|
||||
const result = (res?.result as any) || {};
|
||||
return result.code === 0 ? result.data : [];
|
||||
} catch (e) {
|
||||
console.error('getFavoriteList failed', e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否已收藏
|
||||
*/
|
||||
export async function checkFavorited(worksheetId: string): Promise<boolean> {
|
||||
try {
|
||||
await getUser();
|
||||
const res = await wx.cloud.callFunction({
|
||||
name: 'userFavorites',
|
||||
data: { action: 'check', worksheetId },
|
||||
});
|
||||
const result = (res?.result as any) || {};
|
||||
return result.code === 0 && result.data?.favorited;
|
||||
} catch (e) {
|
||||
console.error('checkFavorited failed', e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量检查是否已收藏,返回 { worksheetId: true } 的 map
|
||||
*/
|
||||
export async function batchCheckFavorited(
|
||||
worksheetIds: string[],
|
||||
): Promise<Record<string, boolean>> {
|
||||
if (!worksheetIds.length) return {};
|
||||
try {
|
||||
await getUser();
|
||||
const res = await wx.cloud.callFunction({
|
||||
name: 'userFavorites',
|
||||
data: { action: 'batchCheck', worksheetIds },
|
||||
});
|
||||
const result = (res?.result as any) || {};
|
||||
return result.code === 0 ? result.data : {};
|
||||
} catch (e) {
|
||||
console.error('batchCheckFavorited failed', e);
|
||||
return {};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user