Commit ed3992a9 authored by hewenhao's avatar hewenhao

init

parents
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 2
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
# 开发环境配置 gh_908821555be8
#构建模式
BUILD_MODE=development
# 微信小程序appid
WEAPP_ID=wx8f25def587982a19
# 服务器接口地址
SERVER_ENDPOINT=http://172.10.61.170
# 腾讯地图接口 api key
TARO_TECENT_LBS_KEY=X3OBZ-OKM3D-I2A4L-P3LQY-7C7ZZ-3KBFG
# 天御验证码App id
TARO_T_CAPTCHA_APP_ID=2034167834
# 本地开发环境端口
DEV_SERVER_PORT=4100
# 输出目录
TARO_OUTPUT_ROOT=dist
# 代码上传机器人
DEPLOY_BOT=5
# 指定开发的分包
DEV_PACKAGES=ALL
# 备注
RELEASE_REMARK=[dev] 操作者:${submitName} 时间:${date} 服务器:${server} 分支:${branchName}
# 极客素质课 生产环境配置
BUILD_MODE=production
# 微信小程序appid
WEAPP_ID=wxb1383b0817e6206b
# 服务器接口地址
SERVER_ENDPOINT=https://geek.jkwljy.com
# 腾讯地图接口 api key
TARO_TECENT_LBS_KEY=X3OBZ-OKM3D-I2A4L-P3LQY-7C7ZZ-3KBFG
# 输出目录
TARO_OUTPUT_ROOT=_production
# 天御验证码App id
TARO_T_CAPTCHA_APP_ID=2022643361
# 代码上传机器人
DEPLOY_BOT=27
# 备注
RELEASE_REMARK=[prod] ${submitName} 在 ${date} 提交
\ No newline at end of file
# 预发环境配置
#构建模式
BUILD_MODE=production
# 微信小程序appid
WEAPP_ID=wxa90a0810c0c52555
# 服务器接口地址
SERVER_ENDPOINT=https://pay.jkwljy.com
# 腾讯地图接口 api key
TARO_TECENT_LBS_KEY=X3OBZ-OKM3D-I2A4L-P3LQY-7C7ZZ-3KBFG
# 天御验证码App id
TARO_T_CAPTCHA_APP_ID=2034167834
# 测试环境变量
Staging=true
# 输出目录
TARO_OUTPUT_ROOT=_staging
# 代码上传机器人
DEPLOY_BOT=13
# 备注
RELEASE_REMARK=[stage] 操作者:${submitName} 时间:${date} 服务器:${server} 分支:${branchName}
# 测试环境配置
#构建模式
BUILD_MODE=production
# 微信小程序appid wxa90a0810c0c52555 wxb1383b0817e6206b
WEAPP_ID=wxb1383b0817e6206b
# 服务器接口地址
SERVER_ENDPOINT=http://172.10.62.70
# 天御验证码App id
TARO_T_CAPTCHA_APP_ID=2034167834
# 腾讯地图接口 api key
TARO_TECENT_LBS_KEY=X3OBZ-OKM3D-I2A4L-P3LQY-7C7ZZ-3KBFG
# 测试环境变量
Testing=true
# 输出目录
TARO_OUTPUT_ROOT=_testing
# 代码上传机器人
DEPLOY_BOT=19
# 备注
RELEASE_REMARK=[test] 操作者:${submitName} 时间:${date} 服务器:${server} 分支:${branchName}
module.exports = {
"extends": ["standard", "taro/preact", "plugin:react/jsx-runtime"],
overrides: [
{
files: ['config/**', 'scripts/**', 'mock/**', 'babel.config.js', '.eslintrc.js'],
rules: {
'import/no-commonjs': 'off',
},
},
],
}
dist/
deploy_versions/
.temp/
.rn_temp/
node_modules/
.DS_Store
/src/app.config.ts
.swc
/mock/routes/user_db.json
.private.*
preview.*
_staging
_production
_testing
/qr_output
/gen-mini-qr.js
registry=http://git.jksxb.cn:8081/repository/geek/
disturl=https://npm.taobao.org/dist
sass_binary_site=https://npm.taobao.org/mirrors/node-sass/
phantomjs_cdnurl=https://npm.taobao.org/mirrors/phantomjs/
fsevents_binary_host_mirror=http://npm.taobao.org/mirrors/fsevents/
// babel-preset-taro 更多选项和默认值:
// https://github.com/NervJS/taro/blob/next/packages/babel-preset-taro/README.md
module.exports = {
presets: [
['taro', {
framework: 'preact',
ts: true
}]
]
}
module.exports = {
env: {
NODE_ENV: '"development"'
},
defineConstants: {
},
mini: {},
h5: {}
}
const path = require('path');
const styleMap = new Map();
let seeds = 100;
const alphabet = 'LDUlv_EQgqiWPKdxztharpfbJcYwBsGZCkuFnOjSHeTmIRVyoXNMA' // 'abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('').sort(() => Math.random() - 0.5).join('');
const len = alphabet.length;
function getShortName(index, order = 0) {
const arr = getAlphabetList(index, len);
const keys = arr.map((item) => alphabet[item]).join('');
if (order !== 0) {
// keys += order;
}
return `${keys}`;
}
const outputRoot = process.env.TARO_OUTPUT_ROOT || 'dist';
const envKeys = Object.keys(process.env);
const envMap = {};
envKeys.forEach((key) => {
if (/^TARO_/.test(key)) {
envMap[`process.env.${key}`] = JSON.stringify(process.env[key]);
}
});
function getAlphabetList(index, lenx = 52) {
const arr = [];
let idx = 0;
let val = index;
do {
idx = val % lenx;
val = Math.floor(val / lenx);
arr.push(idx);
} while (val > lenx);
if (val > 0) {
arr.push(val);
}
return arr.reverse();
}
const config = {
projectName: 'GeekLearnMathWeapp',
date: '2023-3-20',
designWidth: 750,
deviceRatio: {
640: 2.34 / 2,
750: 1,
828: 1.81 / 2
},
alias: {
'@': path.resolve(__dirname, '..', 'src/'),
},
sourceRoot: 'src',
outputRoot: outputRoot,
plugins: [],
defineConstants: {
'process.env.Staging': JSON.stringify(process.env.Staging || false),
'process.env.DEV_SERVER': JSON.stringify(process.env.DEV_SERVER || ''),
'process.env.SERVER_ENDPOINT': JSON.stringify(process.env.SERVER_ENDPOINT || ''),
...envMap,
},
copy: {
patterns: [
],
options: {
}
},
framework: 'preact',
compiler: 'webpack5',
cache: {
enable: false // Webpack 持久化缓存配置,建议开启。默认配置请参考:https://docs.taro.zone/docs/config-detail#cache
},
mini: {
enableSourceMap: process.env.NODE_ENV !== 'production',
postcss: {
pxtransform: {
enable: true,
config: {
}
},
url: {
enable: true,
config: {
limit: 1024 // 设定转换尺寸上限
}
},
cssModules: {
enable: true,
config: {
namingPattern: 'module', // 转换模式,取值为 global/module
generateScopedName: (localName, absoluteFilePath) => { // 'css_[hash:base64:5]'
const setKey = `${localName}##${absoluteFilePath}`;
const val = styleMap.get(setKey);
if (val) {
styleMap.set(setKey, { ...val, count: val.count + 1 });
return getShortName(val.value, 0);
}
seeds += 1;
styleMap.set(setKey, { value: seeds, count: 0 });
return getShortName(seeds, 0);
},
}
}
}
},
h5: {
publicPath: '/',
staticDirectory: 'static',
postcss: {
autoprefixer: {
enable: true,
config: {
}
},
cssModules: {
enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true
config: {
namingPattern: 'module', // 转换模式,取值为 global/module
generateScopedName: '[name]__[local]___[hash:base64:5]'
}
}
}
}
}
module.exports = function (merge) {
if (process.env.NODE_ENV === 'development') {
return merge({}, config, require('./dev'))
}
return merge({}, config, require('./prod'))
}
module.exports = {
env: {
NODE_ENV: '"production"'
},
defineConstants: {
},
mini: {},
h5: {
/**
* WebpackChain 插件配置
* @docs https://github.com/neutrinojs/webpack-chain
*/
// webpackChain (chain) {
// /**
// * 如果 h5 端编译后体积过大,可以使用 webpack-bundle-analyzer 插件对打包体积进行分析。
// * @docs https://github.com/webpack-contrib/webpack-bundle-analyzer
// */
// chain.plugin('analyzer')
// .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin, [])
// /**
// * 如果 h5 端首屏加载时间过长,可以使用 prerender-spa-plugin 插件预加载首页。
// * @docs https://github.com/chrisvfritz/prerender-spa-plugin
// */
// const path = require('path')
// const Prerender = require('prerender-spa-plugin')
// const staticDir = path.join(__dirname, '..', 'dist')
// chain
// .plugin('prerender')
// .use(new Prerender({
// staticDir,
// routes: [ '/pages/index/index' ],
// postProcess: (context) => ({ ...context, outputPath: path.join(staticDir, 'index.html') })
// }))
// }
}
}
/// <reference types="@tarojs/taro" />
declare module '*.png';
declare module '*.gif';
declare module '*.jpg';
declare module '*.jpeg';
declare module '*.svg';
declare module '*.css';
declare module '*.less';
declare module '*.scss';
declare module '*.sass';
declare module '*.styl';
declare namespace NodeJS {
interface ProcessEnv {
TARO_ENV: 'weapp' | 'swan' | 'alipay' | 'h5' | 'rn' | 'tt' | 'quickapp' | 'qq' | 'jd'
}
}
try {
const chalk = require('chalk');
const path = require('path');
const express = require('express');
const routes = require('./routes');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
const rawArgv = process.argv.slice(2);
const args = require('minimist')(rawArgv);
const { host = '0.0.0.0', port = 4000 } = args;
const proxy = require('./proxy');
Object.keys(proxy).forEach((key) => {
app.use(
key,
createProxyMiddleware({
...proxy[key],
}),
);
});
app.use('/static', express.static(path.resolve(__dirname, 'static')));
app.use(express.json()); // for parsing application/json
app.use(express.urlencoded({ extended: true }));
routes.forEach((route) => {
route(app);
});
// eslint-disable-next-line no-unused-vars
app.use((err, req, res, next) => {
res.status(200).json({
code: 1,
msg: err.message,
data: null,
});
});
app.listen(port, host, (err) => {
if (!err) {
console.log(`mock server listen on ${chalk.cyan(`${host}:${port}`)}`);
}
});
} catch (e) {
console.log(e);
process.send(e);
}
/* eslint-disable import/no-commonjs */
const url = require('url');
const server = process.env.SERVER_ENDPOINT;
const { host } = url.parse(server);
const keys = [
'/service-*',
'/api-*',
'/hlw-',
// '/'
];
module.exports = keys.reduce((ret, key) => {
ret[key] = {
target: server, // "http://192.168.32.35:3000/", //process.env.SERVER_ENDPOINT,
logLevel: 'debug',
changeOrigin: true,
headers: { host },
};
return ret;
}, {
'/dev-api/': {
target: 'http://172.10.70.184:8220',
pathRewrite: {
'^/dev-api/': '/',
},
logLevel: 'debug',
changeOrigin: true,
headers: { host },
},
});
const utils = require('../utils');
const fetch = require('node-fetch');
const fs = require('fs');
const path = require('path');
const appid = 'wxb1383b0817e6206b';//'wxa90a0810c0c52555';
const appSecret = '328066e46bc32a8cb2b19d9c00a7699b';//'a382c62b6f714879ef906486fe9556d2';
const dbPath = path.resolve(__dirname, "user_db.json");
module.exports = app => {
app.post('/mock/service-activity-pbl/user/login', async (req, res) => {
await utils.delay();
const code = req.body.code;
try {
const a = await fetch(
`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`
);
const data = await a.json();
if (!fs.existsSync(dbPath)) {
fs.writeFileSync(dbPath, '[]');
}
const userList = JSON.parse(fs.readFileSync(dbPath) || '[]');
const findIndex = userList.findIndex(
item => item.openid === data.openid
);
let userData;
if (findIndex === -1) {
userData = { ...data };
userData.id = utils.randomCode();
userList.push(userData);
} else {
userData = userList[findIndex];
}
fs.writeFileSync(dbPath, JSON.stringify(userList, null, 2));
res.status(200).json({ code: 0, data: { ...userData, token : utils.randomCode(64) } });
} catch (error) {
res.status(200).json({ code: 1, data: null, error: error.message });
}
})
app.post('/mock/service-activity-pbl/user/bind/phone', async (req, res) => {
await utils.delay();
try {
const { code, iv, encryptedData } = req.body;
const a = await fetch(
`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`
);
const data = await a.json();
const sessionKey = data.session_key;
const result = utils.decodeUserPhone(sessionKey, encryptedData, iv, appid);
const userList = JSON.parse(fs.readFileSync(dbPath) || '[]');
const findIndex = userList.findIndex(
item => item.openid === data.openid
);
let userData;
if (findIndex === -1) {
userData = { ...data, phone: result.phoneNumber };
userData.id = utils.randomCode();
userList.push(userData);
} else {
userList[findIndex] = { ...userList[findIndex], phone: result.phoneNumber };
userData = userList[findIndex];
}
fs.writeFileSync(dbPath, JSON.stringify(userList, null, 2));
res.status(200).json({ code: 0, data: userData });
} catch (error) {
res.status(200).json({ code: 1, data: null, error: error.message });
}
})
}
module.exports = [
require('./pbb'),
require('./auth')
]
\ No newline at end of file
const utils = require('../utils')
module.exports = app => {
app.get('/mock/test', async (req, res) => {
await utils.delay()
res.status(200).json({
code: 0,
data: {
hhh: Math.random(),
}
})
})
}
\ No newline at end of file
const crypto = require('crypto');
module.exports = {
delay (cb, tm = 800) {
return new Promise(resolve => {
setTimeout(() => {
resolve()
cb && cb()
}, tm)
})
},
randomCode: (len = 12) => {
return require('crypto')
.createHash('sha1')
.update(`${Math.random()}`)
.update('dd')
.digest('base64')
.replace(/\/|\+|=/g, '_')
.substring(0, len)
},
decodeUserPhone
}
function decodeUserPhone (sKey, encrypted, _iv, appId) {
// base64 decode
const sessionKey = Buffer.from(sKey, 'base64')//new Buffer(this.sessionKey, 'base64');
const encryptedData = Buffer.from(encrypted, 'base64')// new Buffer(encryptedData, 'base64');
const iv = Buffer.from(_iv, 'base64')//new Buffer(iv, 'base64');
try {
// 解密
var decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv)
// 设置自动 padding 为 true,删除填充补位
decipher.setAutoPadding(true)
var decoded = decipher.update(encryptedData, 'binary', 'utf8')
decoded += decipher.final('utf8')
decoded = JSON.parse(decoded)
} catch (err) {
throw new Error('Illegal Buffer')
}
if (decoded.watermark.appid !== appId) {
throw new Error('Illegal Buffer')
}
return decoded
}
\ No newline at end of file
{
"name": "learn-math-weapp",
"version": "1.0.0",
"private": true,
"description": "",
"scripts": {
"deploy": "node scripts/deploy.js",
"build": "node scripts/compile.js",
"dev": "node scripts/compile.js --watch",
"test": "node scripts/test.js"
},
"browserslist": [
"last 3 versions",
"Android >= 4.1",
"ios >= 8"
],
"author": "",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.7.7",
"@geek/skynet-client-wxmini": "^1.1.7",
"@tarojs/components": "3.6.2",
"@tarojs/helper": "3.6.2",
"@tarojs/plugin-framework-react": "3.6.2",
"@tarojs/plugin-platform-alipay": "3.6.2",
"@tarojs/plugin-platform-h5": "3.6.2",
"@tarojs/plugin-platform-jd": "3.6.2",
"@tarojs/plugin-platform-qq": "3.6.2",
"@tarojs/plugin-platform-swan": "3.6.2",
"@tarojs/plugin-platform-tt": "3.6.2",
"@tarojs/plugin-platform-weapp": "3.6.2",
"@tarojs/runtime": "3.6.2",
"@tarojs/shared": "3.6.2",
"@tarojs/taro": "3.6.2",
"easy-peasy": "^5.2.0",
"preact": "^10.5.15",
"qs": "^6.11.1",
"react-redux": "^7.2.0",
"redux": "^4.0.0",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.3.0"
},
"devDependencies": {
"@babel/core": "^7.8.0",
"@prefresh/babel-plugin": "^0.4.1",
"@prefresh/core": "^1.3.4",
"@prefresh/webpack": "^3.2.3",
"@tarojs/cli": "3.6.2",
"@tarojs/webpack5-runner": "3.6.2",
"@types/react": "^18.0.0",
"@types/webpack-env": "^1.13.6",
"@typescript-eslint/eslint-plugin": "^5.20.0",
"@typescript-eslint/parser": "^5.20.0",
"babel-preset-taro": "3.6.2",
"copy-dir": "^1.3.0",
"default-gateway": "^6.0.3",
"dotenv": "^9.0.2",
"eslint": "^8.12.0",
"eslint-config-standard": "^17.0.0",
"eslint-config-taro": "3.6.2",
"eslint-plugin-import": "^2.12.0",
"eslint-plugin-react": "^7.8.2",
"eslint-plugin-react-hooks": "^4.2.0",
"execa": "^5.0.0",
"express": "^4.17.1",
"http-proxy-middleware": "^2.0.0",
"json-templater": "^1.2.0",
"lint-staged": "^13.0.3",
"miniprogram-ci": "^1.9.5",
"node-fetch": "^2.6.1",
"postcss": "^8.4.18",
"stylelint": "9.3.0",
"temp": "^0.9.4",
"typescript": "^4.1.0",
"webpack": "5.69.0",
"validate-commit-msg": "^2.14.0"
},
"gitHooks": {
"pre-commit": "lint-staged",
"commit-msg": "validate-commit-msg"
},
"lint-staged": {
"*.{js,ts,tsx}": "eslint --fix"
},
"resolutions": {
"@types/react": "^17.0.2"
}
}
{
"miniprogramRoot": "./dist",
"projectname": "GeekLearnMathWeapp",
"description": "",
"appid": "wx8f25def587982a19",
"setting": {
"urlCheck": true,
"es6": false,
"enhance": false,
"compileHotReLoad": false,
"postcss": false,
"minified": false
},
"compileType": "miniprogram"
}
\ No newline at end of file
{
"miniprogramRoot": "./",
"projectname": "GeekLearnMathWeapp",
"description": "",
"appid": "touristappid",
"setting": {
"urlCheck": true,
"es6": false,
"postcss": false,
"minified": false
},
"compileType": "miniprogram"
}
/* eslint-disable comma-dangle */
/* eslint-disable quotes */
/* eslint-disable quote-props */
/* eslint-disable indent */
/* Do not edit this file. It is a file generated by script/config-pkgs.js */
export default {
pages: [
'pages/index/index',
],
subPackages: {{packages}},
resizable: true,
preloadRule: {{preloadRule}},
window: {
navigationBarBackgroundColor: '#fff',
navigationBarTitleText: '学习力成长',
navigationBarTextStyle: 'black',
backgroundTextStyle: 'dark',
backgroundColor: '#F3F8FA',
pageOrientation: 'portrait',
},
permission: {
'scope.userLocation': {
desc: '你的位置信息将用于小程序位置接口的效果展示',
},
},
};
const fs = require('fs');
const path = require('path');
const execa = require('execa');
const chalk = require('chalk').default;
const address = require('address');
const chokidar = require('chokidar');
const configEnv = require('./config-env');
const defaultGateway = require('default-gateway');
const envPath = configEnv();
const result = defaultGateway.v4.sync();
const host = address.ip(result && result.interface);
const rawArgv = process.argv.slice(2);
const { target = 'weapp', watch } = require('minimist')(rawArgv);
const resolve = (...args) => path.resolve(__dirname, ...args);
const bin = (name) => resolve(`../node_modules/.bin/${name}`);
const { WEAPP_ID } = process.env;
if (target === 'weapp') {
if (!WEAPP_ID) {
throw new Error('WEAPP_ID required in ', envPath);
}
const projectConfig = require('../project.config.json');
projectConfig.appid = WEAPP_ID;
fs.writeFileSync(
resolve('../project.config.json'),
JSON.stringify(projectConfig, null, 2),
);
}
if (watch) {
const port = process.env.DEV_SERVER_PORT || 4000;
process.env.DEV_SERVER = `http://${host}:${port}`;
let child = createMock(port);
let timer = null;
const restartMockDuration = 1000;
chokidar
.watch('.', { cwd: resolve('../mock'), ignored: ['user_db.json'] })
.on('add', onFolderChange)
.on('change', onFolderChange)
.on('unlink', onFolderChange);
// eslint-disable-next-line no-inner-declarations
function createMock() {
return execa
.node(
resolve('../mock/index.js'),
['--host', host, '--port', port],
{
cwd: resolve('../'),
stdout: 'inherit',
},
)
.on('message', () => {
throw new Error('start mock server fail');
});
}
// eslint-disable-next-line no-inner-declarations
function onFolderChange() {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
timer = null;
if (child && child.kill('SIGKILL')) {
console.log(`${chalk.blue('重启mock服务中...')}`);
}
child = createMock();
}, restartMockDuration);
}
}
process.env.TARO_BUILD_VERSION = require('../package.json').version;
require('./config-pkgs')(process.env.DEV_PACKAGES);
runTaro(target);
function runTaro(_target) {
execa(
bin('taro'),
['build', '--type', _target, watch && '--watch'].filter(Boolean),
{
cwd: resolve('../'),
stdio: 'inherit',
},
)
.once('close', () => {
console.log('...');
process.exit(0);
});
}
const fs = require('fs');
const path = require('path');
const dotevn = require('dotenv');
const crypto = require('crypto');
const minimist = require('minimist');
const chalk = require('chalk');
const rawArgv = process.argv.slice(2);
module.exports = function configEnv() {
const args = minimist(rawArgv);
const { env = 'development', watch } = args;
const envPath = path.resolve(__dirname, '..', `.env.${env}`);
if (!fs.existsSync(envPath)) {
throw new Error('env file not find ', envPath);
}
console.log('using env file:', chalk.red(`.env.${env}`));
dotevn.config({ path: envPath });
if (watch) {
process.env.NODE_ENV = 'development';
} else if (process.env.BUILD_MODE) {
process.env.NODE_ENV = process.env.BUILD_MODE;
}
const hash = crypto.createHash('md5');
hash.update('GEEK-ONLINE-WEAPP-V4');
hash.update(`build-${env}`);
hash.update(`build-${process.env.SERVER_ENDPOINT || ''}`);
process.env.TARO_STORAGE_KEY = hash.digest('base64').substring(0, 5);
return envPath;
};
const renderer = require('json-templater/string');
const fs = require('fs');
const path = require('path');
const productionPreloadRules = {};
const resolvedPkgs = [
// {
// root: "subPackages/mine/",
// pages: [
// "detail/detail",
// "protocol/protocol",
// "login/index",
// "password/password",
// "addStudent/index",
// "accountManage/index",
// "changePhone/index",
// "switchStudent/index",
// "my-group/index",
// "coupon/index",
// "wallet/index",
// "coupon/detail/index"
// ]
// },
];
const pkgs = [
];
function renderTemplate({ packages, preloadRule }) {
const template = fs.readFileSync(
path.resolve(__dirname, 'app.config.ts.tpl'),
{ encoding: 'utf-8' },
);
const result = renderer(template, {
packages: JSON.stringify(packages, null, 2),
preloadRule: JSON.stringify(preloadRule, null, 2),
});
fs.writeFileSync(path.resolve(__dirname, '../src/app.config.ts'), result);
}
if (process.env.NODE_ENV === 'development') {
module.exports = (args) => {
let packages = resolvedPkgs;
if (args === undefined || args === 'ALL') {
packages = resolvedPkgs.concat(pkgs);
} else {
const list = (args ? String(args).split(',') : []).map((c) => `pkgs/${c}`);
packages = resolvedPkgs.concat(
pkgs.filter((item) => list.includes(item.root)),
);
}
renderTemplate({ packages, preloadRule: {} });
};
} else {
module.exports = () => {
renderTemplate({
packages: resolvedPkgs.concat(pkgs),
preloadRule: productionPreloadRules,
});
};
}
const fs = require('fs');
const path = require('path');
const ci = require('miniprogram-ci');
const configEnv = require('./config-env');
const childProcess = require('child_process');
const packageJson = require('../package.json');
configEnv();
const rawArgv = process.argv.slice(2);
const args = require('minimist')(rawArgv);
const compilePath = path.resolve(__dirname, 'compile.js');
const {
version, release, env, builder, branch,
} = args;
const { version: packageVersion } = packageJson;
let _version = packageVersion;
if (release) {
if (version) {
_version = version;
} else {
if (!_version) {
throw new Error(
'version not find @see',
path.resolve(__dirname, '..', 'package.json'),
);
}
const arr = _version
.split('.')
.filter(Boolean)
.reverse();
const index = arr.findIndex((c) => /^\d+$/.test(c));
if (index === -1) {
throw new Error(
'version invalid @see',
path.resolve(__dirname, '..', 'package.json'),
);
}
arr.splice(index, 1, +arr[index] + 1);
_version = arr.reverse().join('.');
}
}
if (packageVersion !== _version) {
packageJson.version = _version;
fs.writeFileSync(
path.resolve(__dirname, '..', 'package.json'),
JSON.stringify(packageJson, null, 2),
);
}
const submitName = builder || childProcess.execSync('git config user.name', {
encoding: 'utf-8',
});
const branchName = branch || childProcess.execSync('git branch --show-current', {
encoding: 'utf-8',
});
console.log('hi', submitName);
console.log('version', _version);
childProcess.execSync(`node ${compilePath} --env=${env}`, {
cwd: path.resolve(__dirname, '../'),
stdio: 'inherit',
});
const { WEAPP_ID } = process.env;
console.log('build finish');
(async () => {
let privateKey = path.resolve(__dirname, '..', `.private.${WEAPP_ID}.key`);
if (!fs.existsSync(privateKey)) {
privateKey = path.resolve(__dirname, '..', '.private.key');
}
const project = new ci.Project({
appid: WEAPP_ID,
type: 'miniProgram',
projectPath: path.resolve(__dirname, '..', process.env.TARO_OUTPUT_ROOT),
privateKeyPath: privateKey,
});
// eslint-disable-next-line no-template-curly-in-string
const remark = process.env.RELEASE_REMARK || '${submitName} 在 ${date} 提交';
const date = new Date().toLocaleString();
const server = process.env.SERVER_ENDPOINT;
const descript = remark
.replace(/\${date}/g, date)
.replace(/\${server}/g, server)
.replace(/\${submitName}/g, submitName)
.replace(/\${branchName}/g, branchName);
await ci.upload({
project,
robot: process.env.DEPLOY_BOT,
version: _version,
desc: descript,
setting: {
codeProtect: false,
es6: false,
minifyWXML: true,
autoPrefixWXSS: false,
},
qrcodeFormat: 'image',
qrcodeOutputDest: path.resolve(__dirname, '..', `preview.${WEAPP_ID}.jpg`),
pagePath: 'pages/index/index',
onProgressUpdate: (res) => {
console.log(res);
},
});
})();
const path = require('path');
const ci = require('miniprogram-ci');
const configEnv = require('./config-env');
const childProcess = require('child_process');
const packageJson = require('../package.json');
configEnv();
const rawArgv = process.argv.slice(2);
const args = require('minimist')(rawArgv);
const { env } = args;
const { version: packageVersion } = packageJson;
const compilePath = path.resolve(__dirname, 'compile.js');
const submitName = childProcess.execSync('git config user.name', {
encoding: 'utf-8',
});
console.log('hi', submitName);
console.log('version', packageVersion);
childProcess.execSync(`node ${compilePath} --env=${env}`, {
cwd: path.resolve(__dirname, '../'),
stdio: 'inherit',
});
const { WEAPP_ID } = process.env;
console.log('build finish');
console.log();
(async () => {
const project = new ci.Project({
appid: WEAPP_ID,
type: 'miniProgram',
projectPath: path.resolve(__dirname, '..', process.env.TARO_OUTPUT_ROOT),
privateKeyPath: path.resolve(__dirname, '..', `.private.${WEAPP_ID}.key`),
});
await ci.upload({
project,
test: true,
robot: process.env.DEPLOY_BOT,
version: packageVersion,
desc: `${submitName} 在${new Date().toLocaleString()} 提交上传`,
setting: {
es6: false,
minifyWXML: true,
autoPrefixWXSS: false,
},
qrcodeFormat: 'image',
qrcodeOutputDest: path.resolve(__dirname, '..', `preview.${WEAPP_ID}.${env}.jpg`),
pagePath: 'pages/mine/mine',
onProgressUpdate: (res) => {
console.log(res);
},
});
})();
import { request } from '@/utils/request';
import qs from 'qs';
type LoginResult = {
phone?: string | null;
/** 用户openId */
openId: string;
/** 用户昵称 */
nickname?: string | null;
/** 用户头像 */
avatarUrl?: string | null;
/** 登录token */
token: string;
/** 用户ID */
id: number;
/** */
unionId: string;
}
/** 静默登录 */
export function silentLoginApi(code: string, recommendId:string) {
return request<LoginResult, { code: string, recommendId:string, }>({
method: 'POST',
url: '/service-activity-pbl/user/login',
data: { code, recommendId },
});
}
export type LoginOption = {
code: string;
iv: string;
encryptedData: string;
errMsg?: string;
channel:number,
channelExtra:{[key:string]:string}
}
/** 绑定用户手机 */
export function login(opts: LoginOption) {
return request<LoginResult, LoginOption>({
method: 'POST',
url: '/service-activity-pbl/user/bind/phone',
data: opts,
});
}
export type UpdateUserInfoOption = {
nickname: string;
avatarUrl: string;
gender?: 2 | 1 | 0;
province: string;
city: string;
}
/** 更新用户信息 */
export function updateUserInfo(opts: UpdateUserInfoOption) {
return request<LoginResult, UpdateUserInfoOption>({
method: 'POST',
url: '/service-activity-pbl/user/info/update',
data: opts,
});
}
export type AuthRelationUser = {
avatarUrl: string;
nickname: string,
phone: string,
id: number,
}
export type AuthRelationItem = {
createTime: string;
fromUser: AuthRelationUser;
fromUserId: number;
id: number;
mark: string;
toUser: AuthRelationUser;
toUserId: number;
}
const baseUrl = '/service-activity-pbl';
export function getMyAuthRelationList(userId: number) {
return request<{ authMeList: AuthRelationItem[], myAuthList: AuthRelationItem[] }, { userId: number }>({
method: 'POST',
url: `${baseUrl}/auth_relation/list?userId=${userId}`,
data: { userId },
});
}
type DeleteAuthRelationOptions = {
userId: number;
relationId: number;
}
export function deleteAuthRelation(opt: DeleteAuthRelationOptions) {
return request<null, DeleteAuthRelationOptions>({
method: 'POST',
url: `${baseUrl}/auth_relation/delete?${qs.stringify(opt)}`,
data: opt,
});
}
type AddAuthRelationOption = {
fromId: number;
mark: string;
toPhone: string;
}
export function addAuthRelation(opt: AddAuthRelationOption) {
return request<null, AddAuthRelationOption>({
method: 'POST',
url: `${baseUrl}/auth_relation/add?${qs.stringify(opt)}`,
data: opt,
});
}
type CreateCodeRet = {
code: string;
expireTime: string
id: string
userId: string | number
}
export function createLoginCode(userId: number) {
return request<CreateCodeRet, { userId: number }>({
method: 'POST',
url: `${baseUrl}/auth_relation/code/create?userId=${userId}`,
data: { userId },
});
}
type TemporaryCodeLoginRet = CreateCodeRet & {
userDTO?: {
avatarUrl: string;
nickname: string;
phone: string;
id: number;
}
}
export function loginByTemporaryCode(code: string) {
return request<TemporaryCodeLoginRet, { code: string }>({
method: 'POST',
url: `${baseUrl}/auth_relation/code/get?code=${code}`,
data: { code },
});
}
export * from './auth';
import { Component, PropsWithChildren } from 'react'
import { StoreProvider } from 'easy-peasy';
import { getUpdateManager, showModal } from '@tarojs/taro';
import { configSkynet } from '@/utils/skynet'
import store from './store';
import './app.scss'
configSkynet();
class App extends Component<PropsWithChildren> {
componentDidMount () {}
componentDidShow () {
if (getUpdateManager) {
const updateManager = getUpdateManager();
if (updateManager) {
updateManager.onCheckForUpdate(() => {});
updateManager.onUpdateReady(() => {
showModal({
title: '更新提示',
content: '新版本已经准备好,确定重启应用?',
showCancel: false,
success() {
updateManager.applyUpdate();
},
});
});
updateManager.onUpdateFailed(() => {
console.log('下载失败');
showModal({
title: '更新失败',
content: '当前网络异常,请稍后重试',
showCancel: false,
});
});
}
} else {
showModal({
title: '提示',
content:
'当前微信版本过低,无法使用全部功能,请升级到最新微信版本后重试。',
showCancel: false,
});
}
}
componentDidHide () {}
// 在 App 类中的 render() 函数没有实际作用
// 请勿修改此函数
render () {
const StoreProviderLocal = StoreProvider as unknown as any;
return (
<StoreProviderLocal store={store}>
{this.props.children}
</StoreProviderLocal>
)
}
}
export default App
import Taro from '@tarojs/taro';
const RE = /^https?:\/\//;
const buildVersion = String(process.env.TARO_BUILD_VERSION) || '\0_not_find';
const WeappConfigUrl = 'https://profile-1257124244.cos.ap-chengdu.myqcloud.com/app_resource/geek_lll_config.json';
const isValidDomain = (domain) => RE.test(domain);
type ServerConfig = {version: string; domain: string}[] | null
let requestInstance: Taro.RequestTask<ServerConfig> | Promise<null | string>;
let _baseUrl: string;
if (process.env.TARO_ENV === 'h5') {
_baseUrl = '.';
} else if (process.env.NODE_ENV === 'development') {
_baseUrl = process.env.DEV_SERVER!;
} else {
_baseUrl = process.env.SERVER_ENDPOINT!;
}
console.log('init server address:', _baseUrl);
export const baseUrl = RE.test(_baseUrl) ? _baseUrl : `http://${_baseUrl}`;
// 输出日志信息
export const noConsole = false;
export const getBaseUrl = () => {
const findBaseUrlFromServer = (): Taro.RequestTask<ServerConfig> | Promise<null| string> => {
if (requestInstance) {
return requestInstance;
}
// 开发阶段不使用服务端配置
if (process.env.SERVER_ENDPOINT === 'https://geek.jkwljy.com') {
console.log('init base url from', WeappConfigUrl);
requestInstance = Taro.request<ServerConfig>({
method: 'GET',
url: WeappConfigUrl,
header: { 'Cache-Control': 'no-cache' },
timeout: 800,
})
.then(({ data }) => {
const serverConfigList = Array.isArray(data) ? data : [];
const find = serverConfigList.find((c) => c.version === buildVersion);
console.log('base url from server', find);
return find && isValidDomain(find.domain) ? find.domain : null;
})
.catch((error) => {
console.log('init base url error', error);
return null;
});
} else {
requestInstance = Promise.resolve(null);
}
return requestInstance;
};
return findBaseUrlFromServer().then((serverBaseUrl) => {
const realServer = serverBaseUrl || baseUrl;
return realServer;
});
};
import { baseUrl } from './server';
const _baseUrl = process.env.SERVER_ENDPOINT === 'https://geek.jkwljy.com' ? baseUrl : 'http://172.10.62.134';
export const SkynetConfig = {
appId: 'learn-math',
appName: '玩转数学小程序',
url: `${_baseUrl}/hlw-data`,
project: 'f13e0406-592b-43bd-b623-69bfb68973eb',
};
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta content="width=device-width,initial-scale=1,user-scalable=no" name="viewport">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-touch-fullscreen" content="yes">
<meta name="format-detection" content="telephone=no,address=no">
<meta name="apple-mobile-web-app-status-bar-style" content="white">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" >
<title>GeekLearnMathWeapp</title>
<script><%= htmlWebpackPlugin.options.script %></script>
</head>
<body>
<div id="app"></div>
</body>
</html>
export default definePageConfig({
navigationBarTitleText: '首页'
})
.index {
flex-direction: column;
width: 100%;
}
import { View, Button, Text } from '@tarojs/components'
import { useStoreActions, useStoreState } from '@/store/hooks'
import styles from './index.module.scss'
const IndexPage = () => {
const num = useStoreState(state => state.counterModel.count)
const add = useStoreActions(actions => actions.counterModel.add)
const dec = useStoreActions(actions => actions.counterModel.dec)
const asyncAdd = useStoreActions(actions => actions.counterModel.asyncAdd)
return (
<View className={styles.index}>
<Button className='add_btn' onClick={() => add()}>+</Button>
<Button className='dec_btn' onClick={() => dec()}>-</Button>
<Button className='dec_btn' onClick={() => asyncAdd()}>async</Button>
<View><Text>{num}</Text></View>
<View><Text>Hello, World</Text></View>
</View>
)
}
export default IndexPage
import { createTypedHooks } from 'easy-peasy';
import { AppStoreModel } from './store-model';
const { useStoreActions, useStoreState } = createTypedHooks<AppStoreModel>();
export { useStoreActions, useStoreState };
import { createStore } from 'easy-peasy';
import storeModel, { AppStoreModel } from './store-model';
const store = createStore<AppStoreModel>(storeModel);
export default store;
import {
action, Action, Computed, computed, Thunk, thunk,
} from 'easy-peasy';
import WithPaging from '@/utils/with-paging';
import { PagingFn } from '@/types';
interface CartModelSlice {
count: number;
test: number[];
addItem: Action<CartModel, any>;
removeItem: Action<CartModel, any>;
asyncAdd: Thunk<CartModel, any, any, any>;
testComputed: Computed<CartModel, number>;
}
interface ListItem {
id: number;
name: number;
}
const api: PagingFn<ListItem, {}> = async () => {
await new Promise((resolve) => {
setTimeout(resolve, 800);
});
return {
code: 0,
sysTime: Date.now(),
data: {
list: new Array(10).fill(0).map((_, index) => ({
id: index,
name: Math.random(),
})) as ListItem[],
total: 400,
hasNextPage: true,
},
};
};
const cartModel = WithPaging<ListItem, CartModelSlice, {}>(api)({
count: 13,
test: [1, 4, 5, 6],
testComputed: computed([(state) => state.count, (state) => state.test], (a, b) => a + b.reduce((ret, item) => ret + item)),
addItem: action((state) => {
state.count += 1;
}),
removeItem: action((state) => {
state.count -= 1;
}),
asyncAdd: thunk(async (actions, _, helpers) => {
const state = helpers.getState();
console.log(state, 111111);
await new Promise((resolve) => {
setTimeout(resolve, 300);
});
console.log('hhhh', helpers.getState());
actions.addItem(0);
}),
});
export default cartModel;
export type CartModel = typeof cartModel;
import {
action, Action, Thunk, thunk,
} from 'easy-peasy';
import { AppStoreModel } from '../store-model'
export interface CounterModel {
count: number;
add: Action<CounterModel, void>;
dec: Action<CounterModel, void>;
asyncAdd: Thunk<CounterModel, void, void, AppStoreModel>;
}
const counterModel: CounterModel = {
count: 0,
add: action((state) => {
state.count = state.count + 1
}),
dec: action((state) => {
state.count = state.count - 1
}),
asyncAdd: thunk(async (actions) => {
await new Promise(resolve => setTimeout(resolve, 2000))
actions.add()
})
};
export default counterModel;
import cartModel from './modules/cart';
import counterModel from './modules/counter';
const appStoreModel = {
cartModel,
counterModel,
};
export default appStoreModel;
type AppStoreModel = typeof appStoreModel
export { AppStoreModel };
import type Taro from '@tarojs/taro';
export type UserInfo = {
userId?: number;
phone?: string | null;
nickname?: string | null;
avatarUrl?: string | null;
expire?: number;
}
export type RequestResultPagingLike<T> = RequestResult<PagingLike<T>>
export type PagingLike<T> = {
list: T[];
hasNextPage: boolean;
total: number;
}
type PagingBaseParam = {
pageNum: number;
pageSize: number;
}
export type PagingFn<T, P> = (
arg: P & PagingBaseParam,
cancelFn?: (task: Taro.RequestTask<RequestResultPagingLike<T>>) => void,
) => Promise<RequestResultPagingLike<T>>
export type ParamFn<P = unknown> = () => P;
export type FormatFn<T = unknown, TT = T> = (arg: T, sysTime: number) => TT;
export type PagingFormatFn<T = unknown, TT = T> = (arg: T, index: number, sysTime: number, list: T[]) => TT;
export type RouteParamsWithShare<T extends Partial<Record<string, string>>> = { scene?: string } & T;
export type RequestRawResult<T> = {
msg?: string;
code: number;
data: T;
}
export type RequestResult<T> = RequestRawResult<T> & {
sysTime: number;
}
export class Deferred<T = unknown> {
private _promise: Promise<T>;
private _resolve: ((arg: T) => void);
private _reject: ((arg: any) => void);
constructor() {
this._promise = new Promise((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
});
}
resolve = (data: T) => {
this._resolve(data);
};
reject = (reason) => {
this._reject(reason);
};
getPromise = (): Promise<T> => this._promise;
}
import Taro from '@tarojs/taro';
import type { UserInfo, RequestRawResult, RequestResult } from '@/types';
import { silentLoginDeferred } from './silent-login';
import { noConsole, getBaseUrl } from '../config/server';
import { getStorage, StorageKeys } from './storage';
const codeMessageMap = {
200: '服务器成功返回请求的数据',
201: '新建或修改数据成功',
202: '一个请求已经进入后台排队(异步任务)',
204: '删除数据成功',
400: '发出的请求有错误,服务器没有进行新建或修改数据的操作',
401: '用户没有权限(令牌、用户名、密码错误)',
403: '用户得到授权,但是访问是被禁止的',
404: '请求不存在',
406: '请求的格式不可得',
410: '请求的资源被永久删除,且不会再得到的',
422: '当创建一个对象时,发生一个验证错误',
500: '服务器发生错误,请检查服务器',
502: '网关错误',
503: '服务不可用,服务器暂时过载或维护',
504: '网关超时',
};
const errorCodeMap = {
};
export type RequestOption<T = unknown, P = unknown> = {
method?: 'GET' | 'POST' | 'DELETE' | 'OPTIONS' | 'PUT';
data: P;
url: string;
baseUrl?: string;
cancelToken?: (arg: Taro.RequestTask<RequestRawResult<T>>) => void;
}
export class BizError<T> extends Error {
data: T;
code: number;
codeMessage: string;
constructor(arg, data: T, code: number, codeMessage: string) {
super(arg);
this.data = data;
this.code = code;
this.codeMessage = codeMessage;
}
}
async function request<T = unknown, P = unknown>(options: RequestOption<T, P>): Promise<RequestResult<T>> {
if (!noConsole) {
console.log(
`${new Date().toLocaleString()}【 M=${options.url} 】P=${JSON.stringify(
options.data,
)}`,
);
}
const header: {
Authorization?: string;
'Content-Type': string;
STUDENTUSERID?: string;
} = {
'Content-Type': 'application/json',
};
const token = getStorage(StorageKeys.token);
const userId = getStorage(StorageKeys.userInfo)?.userId;
if (token) {
header.Authorization = `Bearer ${token}`;
}
if (userId) {
header.STUDENTUSERID = `${userId}`;
}
const doRequest = (baseUrl) => {
const base = options.baseUrl || baseUrl;
console.log('request url:', base + options.url);
const requestTask = Taro.request<RequestRawResult<T>, P>({
url: base + options.url,
data: options.data,
header,
method: options.method ?? 'GET',
});
const { cancelToken } = options;
if (cancelToken) {
cancelToken(requestTask);
}
return requestTask.then((res) => {
const { statusCode, data, header: resultHeader } = res;
if (!noConsole) {
console.log(
`${new Date().toLocaleString()}【 M=${
options.url
} 】【接口响应:】`,
data,
);
}
if (statusCode >= 200 && statusCode < 300) {
if (data.code !== 0) {
throw new BizError(`${data.msg || '请求失败'}`, data.data, data.code, errorCodeMap[data.code]);
}
const date = new Date(resultHeader.Date || resultHeader.date).getTime();
return { ...data, sysTime: date };
} if (statusCode === 401) {
Taro.showModal({
content: '当前状态未登录',
confirmText: '去登录',
cancelText: '稍后',
}).then(({ confirm }) => {
if (confirm) {
Taro.navigateTo({ url: '/pkgs/mine/login/index' });
}
});
throw new Error('登录失效');
} else {
const msg = codeMessageMap[statusCode] || '网络请求错误';
throw new Error(`${msg}`);
}
});
};
return getBaseUrl().then(doRequest);
}
type RequestAfterSilentLoginOption<T, P> = RequestOption<T, P> | ((arg: UserInfo | null) => RequestOption<T, P>)
/** 静默登录后才执行请求 */
export async function requestAfterSilentLogin<T, P = void>(arg: RequestAfterSilentLoginOption<T, P>) {
await silentLoginDeferred.getPromise();
const userInfo = getStorage(StorageKeys.userInfo);
if (typeof arg === 'function') {
// eslint-disable-next-line no-return-await
return await request<T, P>(arg(userInfo));
}
// eslint-disable-next-line no-return-await
return await request<T, P>(arg);
}
export { request };
import { silentLoginApi } from '@/api';
// import store from '@/store';
import Taro from '@tarojs/taro';
import { setProfile } from './skynet';
import { Deferred } from './deferred';
import {
getStorage, StorageKeys, updateStorage,
} from './storage';
const silentLoginDeferred = new Deferred<null>();
async function silentLogin(recommendId:string) {
try {
await Taro.checkSession();
const token = getStorage(StorageKeys.token);
const openId = getStorage(StorageKeys.openid);
const userInfo = getStorage(StorageKeys.userInfo)
if (!token || !openId) { // 未登录
throw new Error('unlogin');
}
setProfile(openId, `${userInfo?.userId}`);
} catch (error) {
console.log('check session', error);
try {
const { code } = await Taro.login();
const { data } = await silentLoginApi(code, recommendId);
updateStorage(StorageKeys.openid, data.openId);
updateStorage(StorageKeys.unionid, data.unionId);
updateStorage(StorageKeys.token, data.token);
setProfile(data.openId, `${data.id}`);
} catch (silentLoginError) {
console.log('silent login error', error);
}
} finally {
silentLoginDeferred.resolve(null);
}
}
export { silentLoginDeferred, silentLogin };
import {
register, report as _report, setOpenId, setProfile as _setProfile,
} from '@geek/skynet-client-wxmini';
import { SkynetConfig } from '@/config/skynet';
export function configSkynet() {
register({
app_id: SkynetConfig.appId,
app_name: SkynetConfig.appName,
project: SkynetConfig.project,
url: SkynetConfig.url,
});
}
export function updateOpenId(openId?: string | null) {
if (openId) {
setOpenId(openId);
}
}
export enum SkynetEvent {
PageView = 'PageView',
PageLeave = 'PageLeave',
}
type Payload<T extends SkynetEvent> =
T extends SkynetEvent.PageLeave ?
{ data: number; }
: T extends SkynetEvent.PageView ?
{ data: string } : never
export function report<T extends SkynetEvent>(eventType: T, payload: Payload<T>) {
_report(eventType, payload);
}
export function setProfile(openId: string, userId: string) {
_setProfile({ user_id: userId, sub_id: userId, open_id: openId });
}
import Taro from '@tarojs/taro';
import type { UserInfo } from '@/types';
const storagePrefix = `${process.env.TARO_STORAGE_KEY}`;
export enum StorageKeys {
/** 用户信息 */
userInfo = 1,
/** token */
token,
/** openid */
openid,
/** unionid */
unionid,
}
type Storage = {
[StorageKeys.userInfo]: UserInfo | null;
[StorageKeys.token]: string | null;
[StorageKeys.openid]: string | null;
[StorageKeys.unionid]: string | null;
}
const store: Storage = {} as Storage;
export function updateStorage<T extends StorageKeys>(key: T, val: Storage[T]) {
store[key] = val;
Taro.setStorageSync(`${storagePrefix}${key}`, val);
}
export function reloadStore() {
try {
[
StorageKeys.openid,
StorageKeys.userInfo,
StorageKeys.token,
StorageKeys.unionid,
].forEach((element) => {
updateStorage(element, Taro.getStorageSync(`${storagePrefix}${element}`) ?? null);
});
} catch (e) {
console.log(e);
}
}
reloadStore();
console.log(store, 1111111)
export function getStorage<T extends StorageKeys>(key: T): Storage[T] | null {
return store[key];
}
import Taro from '@tarojs/taro';
import {
Action, action, Computed, computed, Thunk, thunk,
} from 'easy-peasy';
import { AppStoreModel } from '@/store/store-model';
import { PagingFn, PagingFormatFn, PagingLike } from '@/types';
interface ListModelState {
error: string | null;
isLoad: boolean;
refreshing: boolean;
loading: boolean;
pageSize: number;
total: number;
pageNum: number;
hasNextPage: boolean;
}
type InitParams<L> = Partial<Pick<ListModelState, 'pageSize' | 'pageNum'>> & {
format?: PagingFormatFn<L>
}
type IUnionModel<L, P, M> = ListModelBase<L, P, M> & IPagerWidthParams<L, P, M>;
type ListModelBase<L, P, M> = ListModelState & {
list: L[];
loadMore: Thunk<IUnionModel<L, P, M>, P | void, any, AppStoreModel, Promise<any>>;
refresh: Thunk<IUnionModel<L, P, M>, P | void, any, AppStoreModel, Promise<any>>;
isEmpty: Computed<IUnionModel<L, P, M>, boolean>;
setLoading: Action<IUnionModel<L, P, M>, boolean>;
setRefreshing: Action<IUnionModel<L, P, M>, boolean>;
clearPager: Action<IUnionModel<L, P, M>, string | null | void>;
updateRefreshPager: Action<IUnionModel<L, P, M>, PagingLike<L>>;
updateLoadMorePager: Action<IUnionModel<L, P, M>, PagingLike<L> & { pageNum: number }>;
};
const defaultPageConfig = {
pageSize: 15,
pageNum: 1,
format: <T>(val: T) => val,
};
// 需要自定义参数继承这个
export type IPagerWidthParams<L = {}, P = {}, M = {}> = {
getListParams: Thunk<IUnionModel<L, P, M> & M, void, void, AppStoreModel, Promise<Partial<P>> | Partial<P>>;
}
/**
* 防止传入的model字段 和 默认分页字段冲突
*/
type NoneDuplicate<L, P, M extends object> = {
[K in keyof M]: K extends keyof ListModelBase<L, P, M> ? never : M[K];
}
export default function WithPager<L extends object = {}, M extends object = {}, P extends object = {}>(
func: PagingFn<L, P>,
config: InitParams<L> = defaultPageConfig,
) {
return function creator(arg: NoneDuplicate<L, P, M> = {} as NoneDuplicate<L, P, M>): M & ListModelBase<L, P, M> {
const {
pageNum: initPageNum = defaultPageConfig.pageNum,
pageSize: initPageSize = defaultPageConfig.pageSize,
format = defaultPageConfig.format,
} = config;
const pageUtils: M & ListModelBase<L, P, M> = {
error: null,
loading: false,
refreshing: false,
isLoad: false,
total: 0,
pageNum: initPageNum,
pageSize: initPageSize,
list: [],
hasNextPage: true,
isEmpty: computed(({ total, isLoad }) => total === 0 && isLoad),
setLoading: action((state, payload) => {
state.loading = payload;
}),
setRefreshing: action((state, payload) => {
state.refreshing = payload;
}),
clearPager: action((state, error) => {
state.list = [];
state.hasNextPage = true;
state.total = 0;
state.pageNum = 1;
state.isLoad = false;
if (error !== undefined) {
state.error = error;
}
}),
updateRefreshPager: action((state, payload) => {
state.list = payload.list;
state.hasNextPage = payload.hasNextPage;
state.total = payload.total;
state.pageNum = 1;
state.isLoad = true;
state.error = null;
}),
getListParams: thunk(() => ({})),
updateLoadMorePager: action((state, payload) => {
state.list = [...state.list, ...payload.list];
state.total = payload.total;
state.pageNum = payload.pageNum;
state.hasNextPage = payload.hasNextPage;
state.error = null;
}),
loadMore: thunk(async (actions, payload, helpers) => {
const {
pageSize, pageNum, loading, refreshing, hasNextPage,
} = helpers.getState();
if (loading || refreshing || !hasNextPage) return;
actions.setLoading(true);
const nextPageNum = pageNum + 1;
try {
let storeParams: Partial<P> = {};
try {
const result: Partial<P> = await actions.getListParams();
storeParams = result || {};
} catch (error) {
console.log(error);
}
const params = {
...storeParams,
...(payload || {}),
} as P;
const { data: { list, ...rest }, sysTime } = await func({
...params,
pageNum: nextPageNum,
pageSize,
});
const _list = Array.isArray(list) ? list : [];
await actions.updateLoadMorePager({
...rest,
pageNum: nextPageNum,
list: _list.map((item, index) => format(item, index, sysTime, _list)),
});
} catch (error) {
const msg = error.msg || error.message;
if (msg) {
Taro.showToast({ title: msg });
}
await actions.clearPager(msg);
} finally {
actions.setLoading(false);
}
}),
refresh: thunk(async (actions, payload, helpers) => {
const { refreshing, pageSize, loading } = helpers.getState();
if (refreshing || loading) return;
actions.setRefreshing(true);
try {
let storeParams: Partial<P> = {};
try {
const result: Partial<P> = await actions.getListParams();
storeParams = result || {};
} catch (error) {
console.log(error);
}
const params = { ...(payload || {}), ...storeParams } as P;
const { data: { list, ...rest }, sysTime } = await func({
...params,
pageNum: 1,
pageSize,
});
const _list = Array.isArray(list) ? list : [];
await actions.updateRefreshPager({
...rest,
list: _list.map((item, index) => format(item, index, sysTime, _list)),
});
} catch (error) {
const msg = error.msg || error.message;
if (msg) {
Taro.showToast({ title: msg });
}
await actions.clearPager(msg);
} finally {
actions.setRefreshing(false);
}
}),
...arg,
};
return pageUtils;
};
}
{
"compilerOptions": {
"target": "es2017",
"module": "commonjs",
"removeComments": false,
"preserveConstEnums": true,
"moduleResolution": "node",
"experimentalDecorators": true,
"noImplicitAny": false,
"allowSyntheticDefaultImports": true,
"outDir": "lib",
"noUnusedLocals": true,
"noUnusedParameters": true,
"strictNullChecks": true,
"sourceMap": true,
"baseUrl": ".",
"rootDir": ".",
"jsx": "react-jsx",
"allowJs": true,
"resolveJsonModule": true,
"typeRoots": [
"node_modules/@types",
"global.d.ts"
],
"paths": {
"@/*": ["./src/*"]
},
},
"exclude": [
"node_modules",
"dist"
],
"include": ["./src", "./global.d.ts"],
"compileOnSave": false
}
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment