Skip to content

Commit

Permalink
fix(API): 封装通用api接口工具类
Browse files Browse the repository at this point in the history
  • Loading branch information
nihaojob committed Oct 7, 2024
1 parent da841ed commit eab8880
Show file tree
Hide file tree
Showing 3 changed files with 180 additions and 23 deletions.
142 changes: 142 additions & 0 deletions src/api/apiClass.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
/*
* @Author: 秦少卫
* @Date: 2024-10-07 17:00:17
* @LastEditors: 秦少卫
* @LastEditTime: 2024-10-07 17:00:59
* @Description: api接口格式化工具
*/

import axios, { AxiosInstance, AxiosResponse } from 'axios';
import qs from 'qs';
import _ from 'lodash-es';
const baseURL = import.meta.env.APP_APIHOST;
const tokenKey = 'token';
function getToken() {
const token = localStorage.getItem(tokenKey);
return token;
}

const getValue = (item: any) => {
const newData: any = {
id: item.id,
};

Object.keys(item.attributes).forEach((key) => {
const info = item.attributes[key];
newData[key] = info;
if (_.isObject(info)) {
const itemId = _.get(info, 'data.id');
const itemUrl = _.get(info, 'data.attributes.url');
const itemImgFormats = _.get(info, 'data.attributes.formats');
// id、url、图片 Format 属性新增
if (itemId) {
newData[key + 'Id'] = itemId;
}
if (itemUrl) {
newData[key + 'Url'] = baseURL + itemUrl;
}
if (itemImgFormats) {
addImgFormat(newData, key, itemImgFormats);
}
}
});
return newData;
};

const addImgFormat = (data: any, key: string, item: any) => {
Object.keys(item).forEach((imgKey) => {
data[key + 'Url' + _.capitalize(imgKey)] = baseURL + item[imgKey].url;
});
};

const mapValue = (arr: any) => {
return arr.map((item: any) => getValue(item));
};

interface IPageParams {
[key: string]: any;
pagination?: {
page: number;
pageSize: number;
};
}

export default class ServerApi {
instance: AxiosInstance;
apiPath: string;
constructor(path: string, hasToken?: boolean) {
this.apiPath = path;
this.instance = this._initInstance(hasToken);
}

_initInstance(hasToken?: boolean) {
const instance = axios.create({ baseURL });

// 统一处理请求数据
instance.interceptors.request.use(function (config: any) {
const token = getToken();
if (token && hasToken) {
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
});

// 统一处理返回数据
instance.interceptors.response.use(function (response: AxiosResponse) {
// console.log(, 'response');

if (!response.config.skipResponse as any) {
if (response.data?.data?.attributes) {
response.data.data = getValue(response.data.data);
}
if (response.data?.data?.length) {
response.data.data = mapValue(response.data.data);
}
if (response.data?.meta?.pagination) {
response.data.pagination = response.data.meta.pagination;
delete response.data.meta;
}
}
return response.data;
});
return instance;
}
// 查询详情
get(id: string | number, data = {}) {
return this.instance.get(`${this.apiPath}/${id}?${qs.stringify(data)}`);
}
// 添加
add(data = {}) {
return this.instance.post(this.apiPath, data);
}
// 删除
del(id: string | number) {
return this.instance.delete(`${this.apiPath}/${id}`);
}
// 查找
find(data = {} as IPageParams, pageSize?: number) {
if (pageSize) {
data.pagination = {
page: 1,
pageSize: 50,
};
}
return this.instance.get(`${this.apiPath}/?${qs.stringify(data)}`);
}
// 更新
update(id: string, data = {}) {
return this.instance.put(`${this.apiPath}/${id}`, data);
}

IGet(data = {}, skip = true) {
return this.instance.get(`${this.apiPath}`, {
params: data,
skipResponse: skip,
});
}
IPost(data = {}, skip = true) {
return this.instance.post(`${this.apiPath}`, data, {
skipResponse: skip,
});
}
}
34 changes: 32 additions & 2 deletions src/api/material.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@
* @Author: 秦少卫
* @Date: 2024-04-24 14:07:06
* @LastEditors: 秦少卫
* @LastEditTime: 2024-06-12 21:42:00
* @LastEditTime: 2024-10-07 17:06:16
* @Description: 用户接口登录
*/

import qs from 'qs';
import axios from 'axios';

import ApiClass from './apiClass';

const baseURL = import.meta.env.APP_APIHOST;

const instance = axios.create({ baseURL });
Expand Down Expand Up @@ -42,4 +44,32 @@ export const getTmplTypes = () => instance.get('/api/templ-types');
export const getTmplList = (data: any) => instance.get('/api/templs?' + data);

// 获取banner
export const getBannerList = (data: any) => instance.get('/api/banners?' + data);
// export const getBannerList = (data: any) => instance.get('/api/banners?' + data);

// 新版 API---------------------
// 获取模板列表
export const templsApi = new ApiClass('/api/templs');
// 获取模板动态参数
export const customDynamicsApi = new ApiClass('/api/custom/dynamics');
// 获取模板渲染后的数据
export const customRenderApi = new ApiClass('/api/custom/render');
// 素材接口
export const commonMaterialsApi = new ApiClass('/api/materials');
// 素材分类
export const commonMaterialsTypeApi = new ApiClass('/api/material-types');
// 获取模板类型
export const commonTmplTypeApi = new ApiClass('/api/templ-types');
// 获取模板列表
export const commonTmplApi = new ApiClass('/api/templs');
// 获取组合元素分类
export const commonFontGroupTypeApi = new ApiClass('/api/font-style-types');
// 获取组合元素
export const commonFontGroupApi = new ApiClass('/api/font-styles');
// 获取字体列表
export const commonFontApi = new ApiClass('/api/fonts');
// 获取边框列表
export const commonFontStyleApi = new ApiClass('/api/fontborders');
// 获取画布大小
export const commonSizeApi = new ApiClass('/api/sizes');
// banner接口
export const commonBannerApi = new ApiClass('/api/banners');
27 changes: 6 additions & 21 deletions src/views/template/components/banner.vue
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* @Author: 秦少卫
* @Date: 2024-06-12 16:48:10
* @LastEditors: 秦少卫
* @LastEditTime: 2024-06-12 21:51:40
* @LastEditTime: 2024-10-07 17:05:39
* @Description: 幻灯片
-->
<template>
Expand All @@ -19,15 +19,14 @@
>
<CarouselItem class="img-box" v-for="item in banners" :key="item.id">
<a :href="item.url" target="_blank">
<img :src="item.img" :alt="item.title" />
<img :src="item.imgUrl" :alt="item.title" />
</a>
</CarouselItem>
</Carousel>
</div>
</template>
<script name="Banner" setup>
import { getBannerList } from '@/api/material';
import qs from 'qs';
import { commonBannerApi } from '@/api/material';
const setting = reactive({
autoplay: false,
autoplaySpeed: 2000,
Expand All @@ -37,24 +36,10 @@ const setting = reactive({
arrow: 'hover',
});

import { getMaterialInfoUrl } from '@/hooks/usePageList';

const banners = ref([]);
getBannerList(
qs.stringify({
populate: {
img: '*',
},
})
).then((res) => {
banners.value = res.data.data.map((item) => {
return {
id: item.id,
title: item.attributes.title,
img: getMaterialInfoUrl(item.attributes.img),
url: item.attributes.url,
};
});

commonBannerApi.find({ populate: '*' }).then((res) => {
banners.value = res.data;
});
</script>
<style lang="less" scoped>
Expand Down

0 comments on commit eab8880

Please sign in to comment.