Merge branch 'base' into spa

This commit is contained in:
laifeipeng 2025-04-22 14:45:51 +08:00
commit 1693727f56
31 changed files with 2093 additions and 91 deletions

41
.github/workflows/auto-merge.yml vendored Normal file
View File

@ -0,0 +1,41 @@
name: Auto Merge Base to Other Branches
on:
push:
branches:
- base
workflow_dispatch: # 手动触发
jobs:
auto-merge:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3
with:
fetch-depth: 0
token: ${{ secrets.GH_TOKEN_AUTO_MERGE }}
- name: Merge base into main
run: |
git config user.name "GitHub Actions"
git config user.email "actions@github.com"
git checkout main
git merge base --no-ff -m "Auto merge base into main"
git push origin main
- name: Merge base into i18n
run: |
git config user.name "GitHub Actions"
git config user.email "actions@github.com"
git checkout i18n
git merge base --no-ff -m "Auto merge base into i18n"
git push origin i18n
- name: Merge base into tabbar
run: |
git config user.name "GitHub Actions"
git config user.email "actions@github.com"
git checkout tabbar
git merge base --no-ff -m "Auto merge base into tabbar"
git push origin tabbar

View File

@ -7,3 +7,6 @@ uni-pages.d.ts
# 插件生成的文件
src/pages.json
src/manifest.json
# 忽略自动生成文件
src/service/app/**

11
.vscode/settings.json vendored
View File

@ -36,6 +36,7 @@
"manifest.json": "jsonc" // manifest.json
},
"cSpell.words": [
"Aplipay",
"climblee",
"commitlint",
"dcloudio",
@ -44,19 +45,17 @@
"refresherrefresh",
"scrolltolower",
"tabbar",
"Toutiao",
"unibest",
"uvui",
"WechatMiniprogram"
"Wechat",
"WechatMiniprogram",
"Weixin"
],
"typescript.tsdk": "node_modules\\typescript\\lib",
//
"explorer.fileNesting.enabled": true,
"explorer.fileNesting.expand": false,
"explorer.fileNesting.patterns": {
"*.ts": "$(capture).test.ts, $(capture).test.tsx",
"*.tsx": "$(capture).test.ts, $(capture).test.tsx",
// "*.env": "$(capture).env.*",
"CHANGELOG.md": "CHANGELOG*",
"package.json": "pnpm-lock.yaml,pnpm-workspace.yaml,LICENSE,.gitattributes,.gitignore,.gitpod.yml,CNAME,.npmrc,.browserslistrc",
".eslintrc.cjs": ".eslintignore,.prettierignore,.stylelintignore,.commitlintrc.*,.prettierrc.*,.stylelintrc.*,.eslintrc-auto-import.json,.editorconfig,.commitlint.cjs"
}

View File

@ -45,6 +45,14 @@
注意旧的地址 [codercup](https://github.com/codercup/unibest) 我进不去了,使用新的 [feige996](https://github.com/feige996/unibest)。PR和 issue 也请使用新地址,否则无法合并。
## 平台兼容性
| H5 | IOS | 安卓 | 微信小程序 | 字节小程序 | 快手小程序 | 支付宝小程序 | 钉钉小程序 | 百度小程序 |
| --- | --- | ---- | ---------- | ---------- | ---------- | ------------ | ---------- | ---------- |
| √ | √ | √ | √ | √ | √ | √ | √ | √ |
注意每种 `UI框架` 支持的平台有所不同,详情请看各 `UI框架` 的官网,也可以看 `unibest` 文档。
## ⚙️ 环境
- node>=18
@ -76,7 +84,7 @@
[MIT](https://opensource.org/license/mit/)
Copyright (c) 2024 菲鸽
Copyright (c) 2025 菲鸽
## 捐赠

12
env/.env vendored
View File

@ -5,11 +5,21 @@ VITE_UNI_APPID = 'H57F2ACE4'
VITE_WX_APPID = 'wxa2abb91f64032a2b'
# h5部署网站的base配置到 manifest.config.ts 里的 h5.router.base
VITE_APP_PUBLIC_BASE=/unibest/
VITE_APP_PUBLIC_BASE=/
VITE_SERVER_BASEURL = 'https://ukw0y1.laf.run'
VITE_UPLOAD_BASEURL = 'https://ukw0y1.laf.run/upload'
# 有些同学可能需要在微信小程序里面根据 develop、trial、release 分别设置上传地址,参考代码如下。
# 下面的变量如果没有设置,会默认使用 VITE_SERVER_BASEURL or VITE_UPLOAD_BASEURL
VITE_SERVER_BASEURL__WEIXIN_DEVELOP = 'https://ukw0y1.laf.run'
VITE_SERVER_BASEURL__WEIXIN_TRIAL = 'https://ukw0y1.laf.run'
VITE_SERVER_BASEURL__WEIXIN_RELEASE = 'https://ukw0y1.laf.run'
VITE_UPLOAD_BASEURL__WEIXIN_DEVELOP = 'https://ukw0y1.laf.run/upload'
VITE_UPLOAD_BASEURL__WEIXIN_TRIAL = 'https://ukw0y1.laf.run/upload'
VITE_UPLOAD_BASEURL__WEIXIN_RELEASE = 'https://ukw0y1.laf.run/upload'
# h5是否需要配置代理
VITE_APP_PROXY=false
VITE_APP_PROXY_PREFIX = '/api'

View File

@ -0,0 +1,13 @@
import type { GenerateServiceProps } from 'openapi-ts-request'
export default [
{
schemaPath: 'http://petstore.swagger.io/v2/swagger.json',
serversPath: './src/service/app',
requestLibPath: `import request from '@/utils/request';\n import { CustomRequestOptions } from '@/interceptors/request';`,
requestOptionsType: 'CustomRequestOptions',
isGenReactQuery: true,
reactQueryMode: 'vue',
isGenJavaScript: false,
},
] as GenerateServiceProps[]

View File

@ -1,7 +1,7 @@
{
"name": "unibest",
"type": "commonjs",
"version": "2.5.4",
"version": "2.6.3",
"description": "unibest - 最好的 uniapp 开发模板",
"author": {
"name": "feige996",
@ -69,7 +69,8 @@
"build:quickapp-webview-union": "uni build -p quickapp-webview-union",
"prepare": "git init && husky install",
"type-check": "vue-tsc --noEmit",
"cz": "czg"
"cz": "czg",
"openapi-ts-request": "openapi-ts"
},
"lint-staged": {
"**/*.{html,vue,ts,cjs,json,md}": [
@ -101,6 +102,8 @@
"@dcloudio/uni-mp-weixin": "3.0.0-4020920240930001",
"@dcloudio/uni-mp-xhs": "3.0.0-4020920240930001",
"@dcloudio/uni-quickapp-webview": "3.0.0-4020920240930001",
"@tanstack/vue-query": "^5.62.16",
"abortcontroller-polyfill": "^1.7.8",
"dayjs": "1.11.10",
"pinia": "2.0.36",
"pinia-plugin-persistedstate": "3.2.1",
@ -145,11 +148,12 @@
"eslint-plugin-vue": "^9.32.0",
"husky": "^8.0.3",
"lint-staged": "^15.2.10",
"openapi-ts-request": "^1.1.2",
"postcss": "^8.4.49",
"postcss-html": "^1.7.0",
"postcss-scss": "^4.0.9",
"rollup-plugin-visualizer": "^5.12.0",
"sass": "^1.77.8",
"sass": "1.77.8",
"stylelint": "^16.11.0",
"stylelint-config-html": "^1.1.0",
"stylelint-config-recess-order": "^4.6.0",

858
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,6 @@
<script setup lang="ts">
import { onLaunch, onShow, onHide } from '@dcloudio/uni-app'
import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'
onLaunch(() => {
console.log('App Launch')

View File

@ -49,7 +49,6 @@ export const routeInterceptor = {
uni.addInterceptor('navigateTo', navigateToInterceptor)
uni.addInterceptor('reLaunch', navigateToInterceptor)
uni.addInterceptor('redirectTo', navigateToInterceptor)
uni.addInterceptor('navigateBack', navigateToInterceptor)
uni.addInterceptor('switchTab', navigateToInterceptor)
},
}

View File

@ -1,9 +1,11 @@
import { createSSRApp } from 'vue'
import App from './App.vue'
import store from './store'
import { routeInterceptor, requestInterceptor, prototypeInterceptor } from './interceptors'
import 'virtual:uno.css'
import '@/style/index.scss'
import { VueQueryPlugin } from '@tanstack/vue-query'
import 'virtual:uno.css'
import { createSSRApp } from 'vue'
import App from './App.vue'
import { prototypeInterceptor, requestInterceptor, routeInterceptor } from './interceptors'
import store from './store'
export function createApp() {
const app = createSSRApp(App)
@ -11,6 +13,8 @@ export function createApp() {
app.use(routeInterceptor)
app.use(requestInterceptor)
app.use(prototypeInterceptor)
app.use(VueQueryPlugin)
return {
app,
}

View File

@ -24,7 +24,7 @@
<!-- http://localhost:9000/#/pages/index/request -->
<wd-button @click="run" class="my-6">发送请求</wd-button>
<view class="h-12">
<view class="h-16">
<view v-if="loading">loading...</view>
<block v-else>
<view class="text-xl">请求数据如下</view>
@ -37,6 +37,8 @@
<script lang="ts" setup>
import { getFooAPI, postFooAPI, IFooItem } from '@/service/index/foo'
import { findPetsByStatusQueryOptions } from '@/service/app'
import { useQuery } from '@tanstack/vue-query'
const recommendUrl = ref('http://laf.run/signup?code=ohaOgIX')
@ -50,6 +52,15 @@ const { loading, error, data, run } = useRequest<IFooItem>(() => getFooAPI('菲
immediate: true,
initialData,
})
// 使 vue-query useQuery 使
const {
data: data2,
error: error2,
isLoading: isLoading2,
refetch,
} = useQuery(findPetsByStatusQueryOptions({ params: { status: ['available'] } }))
const reset = () => {
data.value = initialData
}

View File

@ -31,6 +31,7 @@
</template>
<script lang="ts" setup>
import { TestEnum } from '@/typings'
import PLATFORM from '@/utils/platform'
defineOptions({
@ -46,6 +47,7 @@ const description = ref(
// uni API
onLoad(() => {
console.log(author)
console.log(TestEnum.A)
})
</script>

View File

@ -0,0 +1,13 @@
/* eslint-disable */
// @ts-ignore
import * as API from './types';
export function displayStatusEnum(field: API.IStatusEnum) {
return { available: 'available', pending: 'pending', sold: 'sold' }[field];
}
export function displayStatusEnum2(field: API.IStatusEnum2) {
return { placed: 'placed', approved: 'approved', delivered: 'delivered' }[
field
];
}

11
src/service/app/index.ts Normal file
View File

@ -0,0 +1,11 @@
/* eslint-disable */
// @ts-ignore
export * from './types';
export * from './displayEnumLabel';
export * from './pet';
export * from './pet.vuequery';
export * from './store';
export * from './store.vuequery';
export * from './user';
export * from './user.vuequery';

193
src/service/app/pet.ts Normal file
View File

@ -0,0 +1,193 @@
/* eslint-disable */
// @ts-ignore
import request from '@/utils/request';
import { CustomRequestOptions } from '@/interceptors/request';
import * as API from './types';
/** Update an existing pet PUT /pet */
export async function updatePet({
body,
options,
}: {
body: API.Pet;
options?: CustomRequestOptions;
}) {
return request<unknown>('/pet', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
data: body,
...(options || {}),
});
}
/** Add a new pet to the store POST /pet */
export async function addPet({
body,
options,
}: {
body: API.Pet;
options?: CustomRequestOptions;
}) {
return request<unknown>('/pet', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
data: body,
...(options || {}),
});
}
/** Find pet by ID Returns a single pet GET /pet/${param0} */
export async function getPetById({
params,
options,
}: {
// 叠加生成的Param类型 (非body参数openapi默认没有生成对象)
params: API.getPetByIdParams;
options?: CustomRequestOptions;
}) {
const { petId: param0, ...queryParams } = params;
return request<API.Pet>(`/pet/${param0}`, {
method: 'GET',
params: { ...queryParams },
...(options || {}),
});
}
/** Updates a pet in the store with form data POST /pet/${param0} */
export async function updatePetWithForm({
params,
body,
options,
}: {
// 叠加生成的Param类型 (非body参数openapi默认没有生成对象)
params: API.updatePetWithFormParams;
body: {
/** Updated name of the pet */
name?: string;
/** Updated status of the pet */
status?: string;
};
options?: CustomRequestOptions;
}) {
const { petId: param0, ...queryParams } = params;
return request<unknown>(`/pet/${param0}`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
params: { ...queryParams },
data: body,
...(options || {}),
});
}
/** Deletes a pet DELETE /pet/${param0} */
export async function deletePet({
params,
options,
}: {
// 叠加生成的Param类型 (非body参数openapi默认没有生成对象)
params: API.deletePetParams;
options?: CustomRequestOptions;
}) {
const { petId: param0, ...queryParams } = params;
return request<unknown>(`/pet/${param0}`, {
method: 'DELETE',
params: { ...queryParams },
...(options || {}),
});
}
/** uploads an image POST /pet/${param0}/uploadImage */
export async function uploadFile({
params,
body,
file,
options,
}: {
// 叠加生成的Param类型 (非body参数openapi默认没有生成对象)
params: API.uploadFileParams;
body: {
/** Additional data to pass to server */
additionalMetadata?: string;
};
file?: File;
options?: CustomRequestOptions;
}) {
const { petId: param0, ...queryParams } = params;
const formData = new FormData();
if (file) {
formData.append('file', file);
}
Object.keys(body).forEach((ele) => {
const item = (body as { [key: string]: any })[ele];
if (item !== undefined && item !== null) {
if (typeof item === 'object' && !(item instanceof File)) {
if (item instanceof Array) {
item.forEach((f) => formData.append(ele, f || ''));
} else {
formData.append(ele, JSON.stringify(item));
}
} else {
formData.append(ele, item);
}
}
});
return request<API.ApiResponse>(`/pet/${param0}/uploadImage`, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
params: { ...queryParams },
data: formData,
...(options || {}),
});
}
/** Finds Pets by status Multiple status values can be provided with comma separated strings GET /pet/findByStatus */
export async function findPetsByStatus({
params,
options,
}: {
// 叠加生成的Param类型 (非body参数openapi默认没有生成对象)
params: API.findPetsByStatusParams;
options?: CustomRequestOptions;
}) {
return request<API.Pet[]>('/pet/findByStatus', {
method: 'GET',
params: {
...params,
},
...(options || {}),
});
}
/** Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. GET /pet/findByTags */
export async function findPetsByTags({
params,
options,
}: {
// 叠加生成的Param类型 (非body参数openapi默认没有生成对象)
params: API.findPetsByTagsParams;
options?: CustomRequestOptions;
}) {
return request<API.Pet[]>('/pet/findByTags', {
method: 'GET',
params: {
...params,
},
...(options || {}),
});
}

View File

@ -0,0 +1,151 @@
/* eslint-disable */
// @ts-ignore
import { queryOptions, useMutation } from '@tanstack/vue-query';
import type { DefaultError } from '@tanstack/vue-query';
import request from '@/utils/request';
import { CustomRequestOptions } from '@/interceptors/request';
import * as apis from './pet';
import * as API from './types';
/** Update an existing pet PUT /pet */
export function useUpdatePetMutation(options?: {
onSuccess?: (value?: unknown) => void;
onError?: (error?: DefaultError) => void;
}) {
const { onSuccess, onError } = options || {};
const response = useMutation({
mutationFn: apis.updatePet,
onSuccess(data: unknown) {
onSuccess?.(data);
},
onError(error) {
onError?.(error);
},
});
return response;
}
/** Add a new pet to the store POST /pet */
export function useAddPetMutation(options?: {
onSuccess?: (value?: unknown) => void;
onError?: (error?: DefaultError) => void;
}) {
const { onSuccess, onError } = options || {};
const response = useMutation({
mutationFn: apis.addPet,
onSuccess(data: unknown) {
onSuccess?.(data);
},
onError(error) {
onError?.(error);
},
});
return response;
}
/** Find pet by ID Returns a single pet GET /pet/${param0} */
export function getPetByIdQueryOptions(options: {
// 叠加生成的Param类型 (非body参数openapi默认没有生成对象)
params: API.getPetByIdParams;
options?: CustomRequestOptions;
}) {
return queryOptions({
queryFn: async ({ queryKey }) => {
return apis.getPetById(queryKey[1] as typeof options);
},
queryKey: ['getPetById', options],
});
}
/** Updates a pet in the store with form data POST /pet/${param0} */
export function useUpdatePetWithFormMutation(options?: {
onSuccess?: (value?: unknown) => void;
onError?: (error?: DefaultError) => void;
}) {
const { onSuccess, onError } = options || {};
const response = useMutation({
mutationFn: apis.updatePetWithForm,
onSuccess(data: unknown) {
onSuccess?.(data);
},
onError(error) {
onError?.(error);
},
});
return response;
}
/** Deletes a pet DELETE /pet/${param0} */
export function useDeletePetMutation(options?: {
onSuccess?: (value?: unknown) => void;
onError?: (error?: DefaultError) => void;
}) {
const { onSuccess, onError } = options || {};
const response = useMutation({
mutationFn: apis.deletePet,
onSuccess(data: unknown) {
onSuccess?.(data);
},
onError(error) {
onError?.(error);
},
});
return response;
}
/** uploads an image POST /pet/${param0}/uploadImage */
export function useUploadFileMutation(options?: {
onSuccess?: (value?: API.ApiResponse) => void;
onError?: (error?: DefaultError) => void;
}) {
const { onSuccess, onError } = options || {};
const response = useMutation({
mutationFn: apis.uploadFile,
onSuccess(data: API.ApiResponse) {
onSuccess?.(data);
},
onError(error) {
onError?.(error);
},
});
return response;
}
/** Finds Pets by status Multiple status values can be provided with comma separated strings GET /pet/findByStatus */
export function findPetsByStatusQueryOptions(options: {
// 叠加生成的Param类型 (非body参数openapi默认没有生成对象)
params: API.findPetsByStatusParams;
options?: CustomRequestOptions;
}) {
return queryOptions({
queryFn: async ({ queryKey }) => {
return apis.findPetsByStatus(queryKey[1] as typeof options);
},
queryKey: ['findPetsByStatus', options],
});
}
/** Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. GET /pet/findByTags */
export function findPetsByTagsQueryOptions(options: {
// 叠加生成的Param类型 (非body参数openapi默认没有生成对象)
params: API.findPetsByTagsParams;
options?: CustomRequestOptions;
}) {
return queryOptions({
queryFn: async ({ queryKey }) => {
return apis.findPetsByTags(queryKey[1] as typeof options);
},
queryKey: ['findPetsByTags', options],
});
}

72
src/service/app/store.ts Normal file
View File

@ -0,0 +1,72 @@
/* eslint-disable */
// @ts-ignore
import request from '@/utils/request';
import { CustomRequestOptions } from '@/interceptors/request';
import * as API from './types';
/** Returns pet inventories by status Returns a map of status codes to quantities GET /store/inventory */
export async function getInventory({
options,
}: {
options?: CustomRequestOptions;
}) {
return request<Record<string, unknown>>('/store/inventory', {
method: 'GET',
...(options || {}),
});
}
/** Place an order for a pet POST /store/order */
export async function placeOrder({
body,
options,
}: {
body: API.Order;
options?: CustomRequestOptions;
}) {
return request<API.Order>('/store/order', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
data: body,
...(options || {}),
});
}
/** Find purchase order by ID For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions GET /store/order/${param0} */
export async function getOrderById({
params,
options,
}: {
// 叠加生成的Param类型 (非body参数openapi默认没有生成对象)
params: API.getOrderByIdParams;
options?: CustomRequestOptions;
}) {
const { orderId: param0, ...queryParams } = params;
return request<API.Order>(`/store/order/${param0}`, {
method: 'GET',
params: { ...queryParams },
...(options || {}),
});
}
/** Delete purchase order by ID For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors DELETE /store/order/${param0} */
export async function deleteOrder({
params,
options,
}: {
// 叠加生成的Param类型 (非body参数openapi默认没有生成对象)
params: API.deleteOrderParams;
options?: CustomRequestOptions;
}) {
const { orderId: param0, ...queryParams } = params;
return request<unknown>(`/store/order/${param0}`, {
method: 'DELETE',
params: { ...queryParams },
...(options || {}),
});
}

View File

@ -0,0 +1,75 @@
/* eslint-disable */
// @ts-ignore
import { queryOptions, useMutation } from '@tanstack/vue-query';
import type { DefaultError } from '@tanstack/vue-query';
import request from '@/utils/request';
import { CustomRequestOptions } from '@/interceptors/request';
import * as apis from './store';
import * as API from './types';
/** Returns pet inventories by status Returns a map of status codes to quantities GET /store/inventory */
export function getInventoryQueryOptions(options: {
options?: CustomRequestOptions;
}) {
return queryOptions({
queryFn: async ({ queryKey }) => {
return apis.getInventory(queryKey[1] as typeof options);
},
queryKey: ['getInventory', options],
});
}
/** Place an order for a pet POST /store/order */
export function usePlaceOrderMutation(options?: {
onSuccess?: (value?: API.Order) => void;
onError?: (error?: DefaultError) => void;
}) {
const { onSuccess, onError } = options || {};
const response = useMutation({
mutationFn: apis.placeOrder,
onSuccess(data: API.Order) {
onSuccess?.(data);
},
onError(error) {
onError?.(error);
},
});
return response;
}
/** Find purchase order by ID For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions GET /store/order/${param0} */
export function getOrderByIdQueryOptions(options: {
// 叠加生成的Param类型 (非body参数openapi默认没有生成对象)
params: API.getOrderByIdParams;
options?: CustomRequestOptions;
}) {
return queryOptions({
queryFn: async ({ queryKey }) => {
return apis.getOrderById(queryKey[1] as typeof options);
},
queryKey: ['getOrderById', options],
});
}
/** Delete purchase order by ID For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors DELETE /store/order/${param0} */
export function useDeleteOrderMutation(options?: {
onSuccess?: (value?: unknown) => void;
onError?: (error?: DefaultError) => void;
}) {
const { onSuccess, onError } = options || {};
const response = useMutation({
mutationFn: apis.deleteOrder,
onSuccess(data: unknown) {
onSuccess?.(data);
},
onError(error) {
onError?.(error);
},
});
return response;
}

128
src/service/app/types.ts Normal file
View File

@ -0,0 +1,128 @@
/* eslint-disable */
// @ts-ignore
export type ApiResponse = {
code?: number;
type?: string;
message?: string;
};
export type Category = {
id?: number;
name?: string;
};
export type deleteOrderParams = {
/** ID of the order that needs to be deleted */
orderId: number;
};
export type deletePetParams = {
/** Pet id to delete */
petId: number;
};
export type deleteUserParams = {
/** The name that needs to be deleted */
username: string;
};
export type findPetsByStatusParams = {
/** Status values that need to be considered for filter */
status: ('available' | 'pending' | 'sold')[];
};
export type findPetsByTagsParams = {
/** Tags to filter by */
tags: string[];
};
export type getOrderByIdParams = {
/** ID of pet that needs to be fetched */
orderId: number;
};
export type getPetByIdParams = {
/** ID of pet to return */
petId: number;
};
export type getUserByNameParams = {
/** The name that needs to be fetched. Use user1 for testing. */
username: string;
};
export type loginUserParams = {
/** The user name for login */
username: string;
/** The password for login in clear text */
password: string;
};
export type Order = {
id?: number;
petId?: number;
quantity?: number;
shipDate?: string;
/** Order Status */
status?: 'placed' | 'approved' | 'delivered';
complete?: boolean;
};
export type Pet = {
id?: number;
category?: Category;
name: string;
photoUrls: string[];
tags?: Tag[];
/** pet status in the store */
status?: 'available' | 'pending' | 'sold';
};
export enum StatusEnum {
available = 'available',
pending = 'pending',
sold = 'sold',
}
export type IStatusEnum = keyof typeof StatusEnum;
export enum StatusEnum2 {
placed = 'placed',
approved = 'approved',
delivered = 'delivered',
}
export type IStatusEnum2 = keyof typeof StatusEnum2;
export type Tag = {
id?: number;
name?: string;
};
export type updatePetWithFormParams = {
/** ID of pet that needs to be updated */
petId: number;
};
export type updateUserParams = {
/** name that need to be updated */
username: string;
};
export type uploadFileParams = {
/** ID of pet to update */
petId: number;
};
export type User = {
id?: number;
username?: string;
firstName?: string;
lastName?: string;
email?: string;
password?: string;
phone?: string;
/** User Status */
userStatus?: number;
};

150
src/service/app/user.ts Normal file
View File

@ -0,0 +1,150 @@
/* eslint-disable */
// @ts-ignore
import request from '@/utils/request';
import { CustomRequestOptions } from '@/interceptors/request';
import * as API from './types';
/** Create user This can only be done by the logged in user. 返回值: successful operation POST /user */
export async function createUser({
body,
options,
}: {
body: API.User;
options?: CustomRequestOptions;
}) {
return request<unknown>('/user', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
data: body,
...(options || {}),
});
}
/** Get user by user name GET /user/${param0} */
export async function getUserByName({
params,
options,
}: {
// 叠加生成的Param类型 (非body参数openapi默认没有生成对象)
params: API.getUserByNameParams;
options?: CustomRequestOptions;
}) {
const { username: param0, ...queryParams } = params;
return request<API.User>(`/user/${param0}`, {
method: 'GET',
params: { ...queryParams },
...(options || {}),
});
}
/** Updated user This can only be done by the logged in user. PUT /user/${param0} */
export async function updateUser({
params,
body,
options,
}: {
// 叠加生成的Param类型 (非body参数openapi默认没有生成对象)
params: API.updateUserParams;
body: API.User;
options?: CustomRequestOptions;
}) {
const { username: param0, ...queryParams } = params;
return request<unknown>(`/user/${param0}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
params: { ...queryParams },
data: body,
...(options || {}),
});
}
/** Delete user This can only be done by the logged in user. DELETE /user/${param0} */
export async function deleteUser({
params,
options,
}: {
// 叠加生成的Param类型 (非body参数openapi默认没有生成对象)
params: API.deleteUserParams;
options?: CustomRequestOptions;
}) {
const { username: param0, ...queryParams } = params;
return request<unknown>(`/user/${param0}`, {
method: 'DELETE',
params: { ...queryParams },
...(options || {}),
});
}
/** Creates list of users with given input array 返回值: successful operation POST /user/createWithArray */
export async function createUsersWithArrayInput({
body,
options,
}: {
body: API.User[];
options?: CustomRequestOptions;
}) {
return request<unknown>('/user/createWithArray', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
data: body,
...(options || {}),
});
}
/** Creates list of users with given input array 返回值: successful operation POST /user/createWithList */
export async function createUsersWithListInput({
body,
options,
}: {
body: API.User[];
options?: CustomRequestOptions;
}) {
return request<unknown>('/user/createWithList', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
data: body,
...(options || {}),
});
}
/** Logs user into the system GET /user/login */
export async function loginUser({
params,
options,
}: {
// 叠加生成的Param类型 (非body参数openapi默认没有生成对象)
params: API.loginUserParams;
options?: CustomRequestOptions;
}) {
return request<string>('/user/login', {
method: 'GET',
params: {
...params,
},
...(options || {}),
});
}
/** Logs out current logged in user session 返回值: successful operation GET /user/logout */
export async function logoutUser({
options,
}: {
options?: CustomRequestOptions;
}) {
return request<unknown>('/user/logout', {
method: 'GET',
...(options || {}),
});
}

View File

@ -0,0 +1,149 @@
/* eslint-disable */
// @ts-ignore
import { queryOptions, useMutation } from '@tanstack/vue-query';
import type { DefaultError } from '@tanstack/vue-query';
import request from '@/utils/request';
import { CustomRequestOptions } from '@/interceptors/request';
import * as apis from './user';
import * as API from './types';
/** Create user This can only be done by the logged in user. 返回值: successful operation POST /user */
export function useCreateUserMutation(options?: {
onSuccess?: (value?: unknown) => void;
onError?: (error?: DefaultError) => void;
}) {
const { onSuccess, onError } = options || {};
const response = useMutation({
mutationFn: apis.createUser,
onSuccess(data: unknown) {
onSuccess?.(data);
},
onError(error) {
onError?.(error);
},
});
return response;
}
/** Get user by user name GET /user/${param0} */
export function getUserByNameQueryOptions(options: {
// 叠加生成的Param类型 (非body参数openapi默认没有生成对象)
params: API.getUserByNameParams;
options?: CustomRequestOptions;
}) {
return queryOptions({
queryFn: async ({ queryKey }) => {
return apis.getUserByName(queryKey[1] as typeof options);
},
queryKey: ['getUserByName', options],
});
}
/** Updated user This can only be done by the logged in user. PUT /user/${param0} */
export function useUpdateUserMutation(options?: {
onSuccess?: (value?: unknown) => void;
onError?: (error?: DefaultError) => void;
}) {
const { onSuccess, onError } = options || {};
const response = useMutation({
mutationFn: apis.updateUser,
onSuccess(data: unknown) {
onSuccess?.(data);
},
onError(error) {
onError?.(error);
},
});
return response;
}
/** Delete user This can only be done by the logged in user. DELETE /user/${param0} */
export function useDeleteUserMutation(options?: {
onSuccess?: (value?: unknown) => void;
onError?: (error?: DefaultError) => void;
}) {
const { onSuccess, onError } = options || {};
const response = useMutation({
mutationFn: apis.deleteUser,
onSuccess(data: unknown) {
onSuccess?.(data);
},
onError(error) {
onError?.(error);
},
});
return response;
}
/** Creates list of users with given input array 返回值: successful operation POST /user/createWithArray */
export function useCreateUsersWithArrayInputMutation(options?: {
onSuccess?: (value?: unknown) => void;
onError?: (error?: DefaultError) => void;
}) {
const { onSuccess, onError } = options || {};
const response = useMutation({
mutationFn: apis.createUsersWithArrayInput,
onSuccess(data: unknown) {
onSuccess?.(data);
},
onError(error) {
onError?.(error);
},
});
return response;
}
/** Creates list of users with given input array 返回值: successful operation POST /user/createWithList */
export function useCreateUsersWithListInputMutation(options?: {
onSuccess?: (value?: unknown) => void;
onError?: (error?: DefaultError) => void;
}) {
const { onSuccess, onError } = options || {};
const response = useMutation({
mutationFn: apis.createUsersWithListInput,
onSuccess(data: unknown) {
onSuccess?.(data);
},
onError(error) {
onError?.(error);
},
});
return response;
}
/** Logs user into the system GET /user/login */
export function loginUserQueryOptions(options: {
// 叠加生成的Param类型 (非body参数openapi默认没有生成对象)
params: API.loginUserParams;
options?: CustomRequestOptions;
}) {
return queryOptions({
queryFn: async ({ queryKey }) => {
return apis.loginUser(queryKey[1] as typeof options);
},
queryKey: ['loginUser', options],
});
}
/** Logs out current logged in user session 返回值: successful operation GET /user/logout */
export function logoutUserQueryOptions(options: {
options?: CustomRequestOptions;
}) {
return queryOptions({
queryFn: async ({ queryKey }) => {
return apis.logoutUser(queryKey[1] as typeof options);
},
queryKey: ['logoutUser', options],
});
}

View File

@ -8,8 +8,20 @@ export interface IFooItem {
export const getFooAPI = (name: string) => {
return http.get<IFooItem>('/foo', { name })
}
/** GET 请求;支持 传递 header 的范例 */
export const getFooAPI2 = (name: string) => {
return http.get<IFooItem>('/foo', { name }, { 'Content-Type-100': '100' })
}
/** POST 请求 */
export const postFooAPI = (name: string) => {
return http.post<IFooItem>('/foo', { name }, { name })
return http.post<IFooItem>('/foo', { name })
}
/** POST 请求;需要传递 query 参数的范例微信小程序经常有同时需要query参数和body参数的场景 */
export const postFooAPI2 = (name: string) => {
return http.post<IFooItem>('/foo', { name })
}
/** POST 请求;支持 传递 header 的范例 */
export const postFooAPI3 = (name: string) => {
return http.post<IFooItem>('/foo', { name }, { name }, { 'Content-Type-100': '100' })
}

28
src/typings.d.ts vendored Normal file
View File

@ -0,0 +1,28 @@
// 全局要用的类型放到这里
declare global {
type IResData<T> = {
code: number
msg: string
data: T
}
// uni.uploadFile文件上传参数
type IUniUploadFileOptions = {
file?: File
files?: UniApp.UploadFileOptionFiles[]
filePath?: string
name?: string
formData?: any
}
type IUserInfo = {
nickname?: string
avatar?: string
/** 微信的 openid非微信没有这个字段 */
openid?: string
token?: string
}
}
export {} // 防止模块污染

View File

@ -1,29 +1,6 @@
// 全局要用的类型放到这里
// 枚举定义
type IResData<T> = {
code: number
msg: string
data: T
}
// uni.uploadFile文件上传参数
type IUniUploadFileOptions = {
file?: File
files?: UniApp.UploadFileOptionFiles[]
filePath?: string
name?: string
formData?: any
}
type IUserInfo = {
nickname?: string
avatar?: string
/** 微信的 openid非微信没有这个字段 */
openid?: string
token?: string
}
enum TestEnum {
A = 'a',
B = 'b',
export enum TestEnum {
A = '1',
B = '2',
}

View File

@ -46,13 +46,19 @@ export const http = <T>(options: CustomRequestOptions) => {
* GET
* @param url
* @param query query参数
* @param header json格式
* @returns
*/
export const httpGet = <T>(url: string, query?: Record<string, any>) => {
export const httpGet = <T>(
url: string,
query?: Record<string, any>,
header?: Record<string, any>,
) => {
return http<T>({
url,
query,
method: 'GET',
header,
})
}
@ -61,18 +67,21 @@ export const httpGet = <T>(url: string, query?: Record<string, any>) => {
* @param url
* @param data body参数
* @param query query参数post请求也支持query
* @param header json格式
* @returns
*/
export const httpPost = <T>(
url: string,
data?: Record<string, any>,
query?: Record<string, any>,
header?: Record<string, any>,
) => {
return http<T>({
url,
query,
data,
method: 'POST',
header,
})
}

View File

@ -1,10 +1,10 @@
import { pages, subPackages, tabBar } from '@/pages.json'
import { isMp } from './platform'
import { isMpWeixin } from './platform'
const getLastPage = () => {
// getCurrentPages() 至少有1个元素所以不再额外判断
// const lastPage = getCurrentPages().at(-1)
// 上面那个在低版本安卓中打包报错所以改用下面这个【虽然我加了src/interceptions/prototype.ts但依然报错】
// 上面那个在低版本安卓中打包报错,所以改用下面这个【虽然我加了 src/interceptions/prototype.ts但依然报错】
const pages = getCurrentPages()
return pages[pages.length - 1]
}
@ -25,8 +25,8 @@ export const getIsTabbar = () => {
/**
* path redirectPath
* path /pages/login/index
* redirectPath /pages/demo/base/route-interceptor
* path '/pages/login/index'
* redirectPath '/pages/demo/base/route-interceptor'
*/
export const currRoute = () => {
const lastPage = getLastPage()
@ -120,27 +120,27 @@ export const getNeedLoginPages = (): string[] => getAllPages('needLogin').map((p
export const needLoginPages: string[] = getAllPages('needLogin').map((page) => page.path)
/**
* BaseUrl
* baseUrl
*/
export const getEnvBaseUrl = () => {
// 请求基准地址
let baseUrl = import.meta.env.VITE_SERVER_BASEURL
// 小程序端环境区分
if (isMp) {
// 微信小程序端环境区分
if (isMpWeixin) {
const {
miniProgram: { envVersion },
} = uni.getAccountInfoSync()
switch (envVersion) {
case 'develop':
baseUrl = 'https://ukw0y1.laf.run'
baseUrl = import.meta.env.VITE_SERVER_BASEURL__WEIXIN_DEVELOP || baseUrl
break
case 'trial':
baseUrl = 'https://ukw0y1.laf.run'
baseUrl = import.meta.env.VITE_SERVER_BASEURL__WEIXIN_TRIAL || baseUrl
break
case 'release':
baseUrl = 'https://ukw0y1.laf.run'
baseUrl = import.meta.env.VITE_SERVER_BASEURL__WEIXIN_RELEASE || baseUrl
break
}
}
@ -155,21 +155,21 @@ export const getEnvBaseUploadUrl = () => {
// 请求基准地址
let baseUploadUrl = import.meta.env.VITE_UPLOAD_BASEURL
// 小程序端环境区分
if (isMp) {
// 微信小程序端环境区分
if (isMpWeixin) {
const {
miniProgram: { envVersion },
} = uni.getAccountInfoSync()
switch (envVersion) {
case 'develop':
baseUploadUrl = 'https://ukw0y1.laf.run/upload'
baseUploadUrl = import.meta.env.VITE_UPLOAD_BASEURL__WEIXIN_DEVELOP || baseUploadUrl
break
case 'trial':
baseUploadUrl = 'https://ukw0y1.laf.run/upload'
baseUploadUrl = import.meta.env.VITE_UPLOAD_BASEURL__WEIXIN_TRIAL || baseUploadUrl
break
case 'release':
baseUploadUrl = 'https://ukw0y1.laf.run/upload'
baseUploadUrl = import.meta.env.VITE_UPLOAD_BASEURL__WEIXIN_RELEASE || baseUploadUrl
break
}
}

View File

@ -8,10 +8,17 @@ export const platform = __UNI_PLATFORM__
export const isH5 = __UNI_PLATFORM__ === 'h5'
export const isApp = __UNI_PLATFORM__ === 'app'
export const isMp = __UNI_PLATFORM__.startsWith('mp-')
export const isMpWeixin = __UNI_PLATFORM__.startsWith('mp-weixin')
export const isMpAplipay = __UNI_PLATFORM__.startsWith('mp-alipay')
export const isMpToutiao = __UNI_PLATFORM__.startsWith('mp-toutiao')
const PLATFORM = {
platform,
isH5,
isApp,
isMp,
isMpWeixin,
isMpAplipay,
isMpToutiao,
}
export default PLATFORM

76
src/utils/request.ts Normal file
View File

@ -0,0 +1,76 @@
import { CustomRequestOptions } from '@/interceptors/request'
/**
* 请求方法: 主要是对 uni.request openapi-ts-request request
* @param options
* @returns Promise
*/
const http = <T>(options: CustomRequestOptions) => {
// 1. 返回 Promise 对象
return new Promise<T>((resolve, reject) => {
uni.request({
...options,
dataType: 'json',
// #ifndef MP-WEIXIN
responseType: 'json',
// #endif
// 响应成功
success(res) {
// 状态码 2xx参考 axios 的设计
if (res.statusCode >= 200 && res.statusCode < 300) {
// 2.1 提取核心数据 res.data
resolve(res.data as T)
} else if (res.statusCode === 401) {
// 401错误 -> 清理用户信息,跳转到登录页
// userStore.clearUserInfo()
// uni.navigateTo({ url: '/pages/login/login' })
reject(res)
} else {
// 其他错误 -> 根据后端错误信息轻提示
!options.hideErrorToast &&
uni.showToast({
icon: 'none',
title: (res.data as T & { msg?: string })?.msg || '请求错误',
})
reject(res)
}
},
// 响应失败
fail(err) {
uni.showToast({
icon: 'none',
title: '网络错误,换个网络试试',
})
reject(err)
},
})
})
}
/*
* openapi-ts-request request
*/
export default function request<T = unknown>(
url: string,
options: Omit<CustomRequestOptions, 'url'> & {
params?: Record<string, unknown>
headers?: Record<string, unknown>
},
) {
const requestOptions = {
url,
...options,
}
if (options.params) {
requestOptions.query = requestOptions.params
delete requestOptions.params
}
if (options.headers) {
requestOptions.header = options.headers
delete requestOptions.headers
}
return http<T>(requestOptions)
}

View File

@ -20,7 +20,8 @@
"@uni-helper/uni-types",
"@types/wechat-miniprogram",
"wot-design-uni/global.d.ts",
"z-paging/types"
"z-paging/types",
"./src/typings.d.ts"
]
},
"vueCompilerOptions": {

View File

@ -1,8 +1,7 @@
import path from 'node:path'
import { execSync } from 'node:child_process'
import dayjs from 'dayjs'
import { defineConfig, loadEnv } from 'vite'
import Uni from '@dcloudio/vite-plugin-uni'
import dayjs from 'dayjs'
import path from 'node:path'
import { defineConfig, loadEnv } from 'vite'
// @see https://uni-helper.js.org/vite-plugin-uni-pages
import UniPages from '@uni-helper/vite-plugin-uni-pages'
// @see https://uni-helper.js.org/vite-plugin-uni-layouts
@ -13,9 +12,9 @@ import UniPlatform from '@uni-helper/vite-plugin-uni-platform'
// @see https://github.com/uni-helper/vite-plugin-uni-manifest
import UniManifest from '@uni-helper/vite-plugin-uni-manifest'
// @see https://unocss.dev/
import { visualizer } from 'rollup-plugin-visualizer'
import UnoCSS from 'unocss/vite'
import AutoImport from 'unplugin-auto-import/vite'
import { visualizer } from 'rollup-plugin-visualizer'
import ViteRestart from 'vite-plugin-restart'
import { copyNativeRes } from './vite-plugins/copyNativeRes'