Skip to content

Commit

Permalink
feat(projects): service and proxy
Browse files Browse the repository at this point in the history
  • Loading branch information
honghuangdc committed Nov 4, 2023
1 parent b76329b commit ed68c8f
Show file tree
Hide file tree
Showing 22 changed files with 245 additions and 20 deletions.
2 changes: 2 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"cSpell.words": [
"Antd",
"antv",
"apifox",
"clsx",
"colord",
"consola",
Expand All @@ -17,6 +18,7 @@
"Laba",
"localforage",
"LOCALSTORAGE",
"MEDZ",
"nocheck",
"nprogress",
"ofetch",
Expand Down
1 change: 1 addition & 0 deletions build/config/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './proxy';
38 changes: 38 additions & 0 deletions build/config/proxy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import type { ProxyOptions } from 'vite';
import { createServiceConfig, createProxyPattern } from '../../env.config';

/**
* set http proxy
* @param env - the current env
*/
export function createViteProxy(env: Env.ImportMeta) {
const isEnableHttpProxy = env.VITE_HTTP_PROXY === 'Y';

if (!isEnableHttpProxy) return undefined;

const { baseURL, otherBaseURL } = createServiceConfig(env);

const defaultProxyPattern = createProxyPattern();

const proxy: Record<string, ProxyOptions> = {
[defaultProxyPattern]: {
target: baseURL,
changeOrigin: true,
rewrite: path => path.replace(new RegExp(`^${defaultProxyPattern}`), '')
}
};

const otherURLEntries = Object.entries(otherBaseURL);

for (const [key, url] of otherURLEntries) {
const proxyPattern = createProxyPattern(key);

proxy[proxyPattern] = {
target: url,
changeOrigin: true,
rewrite: path => path.replace(new RegExp(`^${proxyPattern}`), '')
};
}

return proxy;
}
1 change: 0 additions & 1 deletion build/index.ts

This file was deleted.

44 changes: 44 additions & 0 deletions env.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* create service config by current env
* @param env the current env
*/
export function createServiceConfig(env: Env.ImportMeta) {
const mockURL = 'https://mock.apifox.com/m1/3109515-0-default';

const serviceConfigMap = {
dev: {
baseURL: mockURL,
otherBaseURL: {
demo: 'http://localhost:9528'
}
},
test: {
baseURL: mockURL,
otherBaseURL: {
demo: 'http://localhost:9529'
}
},
prod: {
baseURL: mockURL,
otherBaseURL: {
demo: 'http://localhost:9530'
}
}
} satisfies App.Service.ServiceConfigMap;

const { VITE_SERVICE_ENV = 'dev' } = env;

return serviceConfigMap[VITE_SERVICE_ENV];
}

/**
* get proxy pattern of service url
* @param key if not set, will use the default key
*/
export function createProxyPattern(key?: string) {
if (!key) {
return '/proxy';
}

return `/proxy-${key}`;
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"@sa/color-palette": "workspace:*",
"@sa/hooks": "workspace:*",
"@sa/materials": "workspace:*",
"@sa/request": "workspace:^",
"@sa/utils": "workspace:*",
"@vueuse/core": "10.5.0",
"ant-design-vue": "4.0.6",
Expand Down
10 changes: 10 additions & 0 deletions packages/request/src/axios/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import axios from 'axios';
import type { CreateAxiosDefaults } from 'axios';

export function createAxios(config?: CreateAxiosDefaults) {
const instance = axios.create(config);

return instance;
}

export default createAxios;
12 changes: 3 additions & 9 deletions packages/request/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
import { ofetch } from 'ofetch';
import type { FetchOptions } from 'ofetch';
import { createAxios } from './axios';
import { createOfetch } from './ofetch';

export function createRequest(options: FetchOptions) {
const request = ofetch.create(options);

return request;
}

export default createRequest;
export { createAxios, createOfetch };
Empty file removed packages/request/src/ofetch.ts
Empty file.
10 changes: 10 additions & 0 deletions packages/request/src/ofetch/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { ofetch } from 'ofetch';
import type { FetchOptions } from 'ofetch';

export function createOfetch(options: FetchOptions) {
const request = ofetch.create(options);

return request;
}

export default createOfetch;
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions src/service/api/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { request } from '../request';

/**
* login
* @param userName user name
* @param password password
*/
export function fetchLogin(userName: string, password: string) {
return request<App.Service.Response<Api.Auth.LoginToken>>({
url: '/auth/login',
method: 'post',
data: {
userName,
password
}
});
}
2 changes: 2 additions & 0 deletions src/service/api/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './auth';
// export * from './route';
File renamed without changes.
15 changes: 15 additions & 0 deletions src/service/request/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { createAxios } from '@sa/request';
import { createServiceConfig, createProxyPattern } from '~/env.config';

const { baseURL, otherBaseURL } = createServiceConfig(import.meta.env);

const isHttpProxy = import.meta.env.VITE_HTTP_PROXY === 'Y';

export const request = createAxios({
baseURL: isHttpProxy ? createProxyPattern() : baseURL,
headers: {
apifoxToken: 'XL299LiMEDZ0H5h3A29PxwQXdMJqWyY2'
}
});

export const demoRequest = createAxios({ baseURL: isHttpProxy ? createProxyPattern('demo') : otherBaseURL.demo });
22 changes: 22 additions & 0 deletions src/typings/api.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* namespace Api
* @description all backend api type
*/
declare namespace Api {
/**
* namespace Auth
* @description backend api module: "auth"
*/
namespace Auth {
interface LoginToken {
token: string;
refreshToken: string;
}
}

/**
* namespace Route
* @description backend api module: "route"
*/
namespace Route {}
}
50 changes: 50 additions & 0 deletions src/typings/app.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ declare namespace App {
};
}

/**
* global namespace
*/
namespace Global {
type AntdMenu = NonNullable<import('ant-design-vue').ItemType>;
type AntSubMenu = import('ant-design-vue/es/menu/src/interface').SubMenuType;
Expand Down Expand Up @@ -193,4 +196,51 @@ declare namespace App {
(key: I18nKey, named: Record<string, unknown>, defaultMsg: string): string;
}
}

/**
* service namespace
*/
namespace Service {
/**
* the backend service env type
*/
type EnvType = 'dev' | 'test' | 'prod';

/**
* the backend service config
*/
interface ServiceConfig {
/**
* the backend service base url
*/
baseURL: string;
/**
* other backend service base url map
*/
otherBaseURL: Record<string, string>;
}

/**
* the backend service config map
*/
type ServiceConfigMap = Record<EnvType, ServiceConfig>;

/**
* the backend service response data
*/
type Response<T = unknown> = {
/**
* the backend service response code
*/
code: string;
/**
* the backend service response message
*/
message: string;
/**
* the backend service response data
*/
data: T;
};
}
}
2 changes: 2 additions & 0 deletions src/typings/common.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,6 @@ declare namespace Common {
* @property label: the option label
*/
type Option<K> = { value: K; label: string };

type YesOrNo = 'Y' | 'N';
}
16 changes: 9 additions & 7 deletions src/typings/env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
* @description it is used to declare the type of the import.meta object
*/
declare namespace Env {
type YesOrNo = 'Y' | 'N';

/**
* the router history mode
*/
Expand All @@ -26,11 +24,6 @@ declare namespace Env {
* the description of the application
*/
readonly VITE_APP_DESC: string;
/**
* whether to enable the http proxy
* @description only valid in the development environment
*/
readonly VITE_HTTP_PROXY?: YesOrNo;
/**
* the router history mode
*/
Expand All @@ -44,6 +37,15 @@ declare namespace Env {
* @description this prefix is start with the icon prefix
*/
readonly VITE_ICON_LOCAL_PREFIX: 'local-icon';
/**
* whether to enable the http proxy
* @description only valid in the development environment
*/
readonly VITE_HTTP_PROXY?: Common.YesOrNo;
/**
* the back service env
*/
readonly VITE_SERVICE_ENV?: App.Service.EnvType;
/**
* the auth route mode
* - static: the auth routes is generated in front-end
Expand Down
12 changes: 11 additions & 1 deletion src/views/home/index.vue
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
<script setup lang="ts"></script>
<script setup lang="ts">
// import { fetchLogin } from '@/service/api';
// async function start() {
// const data = await fetchLogin('Soybean', '1234545');
// console.log(data);
// }
// start();
</script>

<template>
<LookForward />
Expand Down
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"strictNullChecks": true,
"forceConsistentCasingInFileNames": true,
"paths": {
"~/*": ["./*"],
"@/*": ["./src/*"]
},
"types": [
Expand Down
6 changes: 4 additions & 2 deletions vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { fileURLToPath, URL } from 'node:url';
import { defineConfig, loadEnv } from 'vite';
import { setupVitePlugins } from './build';
import { setupVitePlugins } from './build/plugins';
import { createViteProxy } from './build/config';

export default defineConfig(configEnv => {
const viteEnv = loadEnv(configEnv.mode, process.cwd()) as unknown as Env.ImportMeta;
Expand All @@ -17,7 +18,8 @@ export default defineConfig(configEnv => {
server: {
host: '0.0.0.0',
port: 9527,
open: true
open: true,
proxy: createViteProxy(viteEnv)
},
build: {
reportCompressedSize: false,
Expand Down

0 comments on commit ed68c8f

Please sign in to comment.