Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,5 @@ $RECYCLE.BIN/

# Node.js
node_modules/

miniprogram_npm/
216 changes: 216 additions & 0 deletions api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
const baseUri = "https://market-staging.huww98.cn/api";
// const baseUri = "http://localhost:8080";

const ErrorCode = {
InvalidJwt: 'invalid-jwt',
}

export class ApiError extends Error {
constructor(code, message) {
super(message);
this.code = code;
this.message = message;
}
}

function readApiResponse(response) {
const json = response.data;
if (response.statusCode != 200) {
if (json.errorCode) {
throw new ApiError(json.errorCode, json.message);
}
throw new Error("意外的错误");
}
return json;
}

function buildUri(path) {
return baseUri + path;
}

function callApi(path, init) {
let builtUri = buildUri(path);
if (init) {
let builtQuery = init.query;
if (init.query) {
delete init.query;
}
if (init.paging) {
builtQuery = {
page: init.paging.page,
size: init.paging.size || 10,
...builtQuery
}
}
if (builtQuery) {
const params = Object.entries(builtQuery).map(([key, value]) => `${key}=${encodeURIComponent(value)}`);
builtUri += "?" + Array.prototype.join.call(params, "&");
}
}

return new Promise((resolve, reject) => {
wx.request({
...init,
url: builtUri,
success: resolve,
fail: reject
})
}).then(readApiResponse);
}

function callApiWithAuthorization(path, init) {
const doCallApi = (jwt) => {
const builtInit = init || {};
builtInit.header = {
"Authorization": "Bearer " + jwt,
...builtInit.header
}
return callApi(path, builtInit);
}
const loginAndCallApi = () => {
return login().then(() => {
doCallApi(getJwt())
});
}
const jwt = getJwt();
let callApiPromise;
if(jwt) {
return doCallApi(jwt).catch(e => {
if (e.errorCode == "invalid-jwt") {
logout();
return loginAndCallApi()
}
throw e;
});
} else {
return loginAndCallApi();
}
}

function callApiWarpper(method, path, body, init) {
const builtInit = {
method,
...init
}
if (body) {
builtInit.data = body;
}
if (builtInit && builtInit.withAuthorization) {
delete builtInit.withAuthorization;
return callApiWithAuthorization(path, builtInit);
} else {
return callApi(path, builtInit);
}
}

function getApi(path, init) {
return callApiWarpper('GET', path, null, init);
}

function postApi(path, body, init) {
return callApiWarpper('POST', path, body, init);
}

function putApi(path, body, init) {
return callApiWarpper('PUT', path, body, init);
}

const jwtStorageKey = "JWT";
export function getJwt() {
return wx.getStorageSync(jwtStorageKey);
}

let loginPromise = null;

export function login() {
if (loginPromise != null) {
return loginPromise;
}
loginPromise = new Promise((resolve, reject) => {
wx.login({
success(res) {
if (res.code) {
resolve(res.code);
} else {
reject(res);
}
},
fail: reject
})
}).then(code => postApi("/wechat/login", { code }))
.then(result =>{
wx.setStorageSync(jwtStorageKey, result.jwt);
loginPromise = null;
});
return loginPromise;
}

export function logout() {
wx.removeStorageSync(jwtStorageKey);
}

export function hasLogedIn() {
return getJwt() !== null;
}

export function getAllCategories() {
return getApi("/categories");
}

export function getAllGoodsInCategory(categoryId, page) {
return getApi(`/categories/${categoryId}/goods`, {
paging: { page }
});
}

export function getGoods(goodsId) {
return getApi(`/goods/${goodsId}`);
}

export function uploadFile(localPath) {
const uri = buildUri('/wechat/uploadfile');
return new Promise((resolve, reject) => wx.uploadFile({
url: uri,
filePath: localPath,
name: 'file',
success: resolve,
fail: reject
})).then(res => {
res.data = JSON.parse(res.data)
return readApiResponse(res);
});
}

export function createGoods(goodsDescription) {
return postApi('/goods', goodsDescription, { withAuthorization: true });
}

export function getAllFavorite(page) {
return getApi('/goods/favorite', {
withAuthorization: true,
paging: { page }
});
}

export function addToFavorite(goodsId) {
return postApi(`/goods/${goodsId}/addToFavorite`, null, { withAuthorization: true });
}

export function deleteFromFavorite(goodsId) {
return postApi(`/goods/${goodsId}/deleteFromFavorite`, null, { withAuthorization: true });
}

export function getAllMy(page) {
return getApi('/goods/my', {
withAuthorization: true,
paging: { page }
});
}

export function getMy(descriptionId) {
return getApi(`/goods/my/${descriptionId}`, { withAuthorization: true });
}

export function updateGoods(goodsId, description) {
return putApi(`/goods/${goodsId}`, description, { withAuthorization: true });
}
22 changes: 5 additions & 17 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,10 @@
import { login, getAllCategories } from "./api.js"

App({
globalData: {

allCategoriesPromise: getAllCategories()
},
onLaunch: function () {
wx.login({
success: res => {
wx.request({
url: 'https://market-staging.huww98.cn/api/wechat/login',
method: 'POST',
data: {
code: res.code
},
success: function (loginResult) {
console.log(loginResult.statusCode);
console.log(loginResult.data);
}
});
}
});
onLaunch() {
login();
}
})
38 changes: 32 additions & 6 deletions app.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
{
"pages": [
"pages/index/index",
"pages/list/list",
"pages/published/published",
"pages/post/post",
"pages/detail/detail"
"pages/detail/detail",
"pages/i/i",
"pages/favorite/favorite",
"pages/about/about",
"pages/post/selectCategory",
"pages/post/selectArea"
],
"window": {
"backgroundColor": "#0071BD",
Expand All @@ -19,17 +24,38 @@
"text": "主页"
},
{
"pagePath": "pages/post/post",
"text": "发布"
"pagePath": "pages/i/i",
"text": ""
}
],
"color": "#cccccc",
"selectedColor": "#00b26a"
},
"networkTimeout": {
"request": 10000,
"request": 20000,
"connectSocket": 10000,
"uploadFile": 10000,
"uploadFile": 60000,
"downloadFile": 10000
},
"usingComponents": {
"van-button": "vant-weapp/button",
"van-icon": "vant-weapp/icon",
"van-tab": "vant-weapp/tab",
"van-tabs": "vant-weapp/tabs",
"van-panel": "vant-weapp/panel",
"van-cell": "vant-weapp/cell",
"van-cell-group": "vant-weapp/cell-group",
"van-slider": "vant-weapp/slider",
"van-progress": "vant-weapp/progress",
"van-checkbox": "vant-weapp/checkbox",
"van-checkbox-group": "vant-weapp/checkbox-group",
"van-radio": "vant-weapp/radio",
"van-radio-group": "vant-weapp/radio-group",
"van-search": "vant-weapp/search",
"van-tag": "vant-weapp/tag",
"van-field": "vant-weapp/field",
"van-popup": "vant-weapp/popup",
"van-swipe-cell": "vant-weapp/swipe-cell",
"van-loading": "vant-weapp/loading"
}
}
17 changes: 16 additions & 1 deletion app.wxss
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
@import "style/weui.wxss";
@import "miniprogram_npm/vant-weapp/common/index.wxss";

.container {
display: flex;
Expand All @@ -7,6 +7,21 @@
box-sizing: border-box;
}

.no-item {
height: 40vh;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}

.no-more-item {
width: 100%;
text-align: center;
padding-top: 20px;
padding-bottom: 25px;
}

page {
background-color: #f8f8f8;
font-size: 16px;
Expand Down
23 changes: 23 additions & 0 deletions behaviors/apiCall.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
export default Behavior({
data: {
loading: false,
loadingCount: 0
},
methods: {
callApi(promise) {
this.setData({
loading: true,
loadingCount: this.data.loadingCount + 1
});
const exitLoading = () => {
const loadingCount = this.data.loadingCount - 1
this.setData({
loading: loadingCount > 0,
loadingCount
});
}
promise.then(exitLoading, exitLoading);
return promise;
}
}
})
21 changes: 21 additions & 0 deletions behaviors/navigationBarLoading.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
export default Behavior({
observers: {
loading() {
this.syncNavigationBarLoading();
}
},
pageLifetimes: {
show() {
this.syncNavigationBarLoading();
},
},
methods: {
syncNavigationBarLoading() {
if (this.data.loading) {
wx.showNavigationBarLoading();
} else {
wx.hideNavigationBarLoading();
}
}
}
})
Loading