yg-tools
Version:
some convenient APIs and Methods for Youngon
160 lines (122 loc) • 3.28 kB
Markdown
# YGTools
> some convenient APIs and Methods for Youngon
## How to use ?
- install
```shell
yarn add yg-tools -S
```
or
```shell
npm install yg-tools -S
```
- import `yg-tools` to your `Youngon Project`
```ts
import YGTools, { YGModels, YGTypes, GlobalConfig } from "yg-tools";
```
- init `YGTools`
```ts
/**IGlobalConfig**/
const configOptions = {
// 环境上下文: wx | qq | Taro | uni
context: wx,
// api 接口地址
baseUrl: "",
// 接口鉴权 token
authToken: "",
// 小程序首页地址
mpIndexPath: "",
// 小程序登录页面地址
mpAccountPath: "",
// 全局接口错误处理
globalAPIErrorHandle() {},
};
const { APIs, Utils } = YGTools.createYGTools(configOptions);
```
IGlobalConfig type as follow:
```ts
interface IGlobalConfig<
R extends HttpResponseOptionWrapper<HttpResponseOption> = HttpResponseOptionWrapper<HttpResponseOption>
> {
/**
* 上下文环境
* 小程序中可以是 wx | my | qq | dd | tt | swan | Taro | uni
*/
context: APIContext<R>;
/**
* api 域名
*/
baseUrl: string;
/**
* 接口 token
*/
authToken: string;
/**
* 小程序首页地址
*/
mpIndexPath: string;
/**
* 小程序帐号设置页面地址
*/
mpAccountPath: string;
/**
* 全局接口错误处理
*/
globalAPIErrorHandle: (msg: string, err?: any) => void;
}
```
- in the web project, you can use WebContext
```ts
const configOptions = new GlobalConfig().useWebContext(webContextOpts);
// webContextOpts is APIContext type or undefined
const { APIs, Utils } = new YGTools(configOptions);
```
APIContext type as follow:
```ts
interface APIContext<
R extends HttpResponseOptionWrapper<HttpResponseOption> = HttpResponseOptionWrapper<HttpResponseOption>
> extends Record<string, any> {
request: (options: HttpRequestOption) => Promise<R>;
showToast: Function;
login: Function;
switchTab: Function;
getStorageSync: Function;
setStorageSync: Function;
removeStorageSync: Function;
clearStorageSync: Function;
}
```
## Custom YGTools
```ts
import YGTools, { YGModels, YGTypes, YGAPIs, YGUtils, GlobalConfig, LDKey } from "yg-tools";
class CustomAPIs extends YGAPIs {
getMyCustomData(id: number) {
return this.YGR.Req({ url: `/example/get/data/url?id=${id}`, method: 'GET', })
}
postMyCustomData(data: Record<string, any>) {
return this.YGR.Req({ url: '/example/post/data/url', method: 'POST', data })
}
// any your custom api request methods...
}
class CustomLDK extends LDKey {
static UserNameKey = 'username'
// any your custom keys of LocalData for Storage...
}
class CustomUtils extends YGUtils<typeof CustomLDK> {
getCurrentTime = () => Date.now().toLocaleString()
// any your custom properties or methods or functions...
}
const iYGTools = YGTools.createCustomYGTools<
typeof CustomAPIs,
typeof CustomLDK,
typeof CustomUtils,
CustomAPIs,
CustomUtils
>({
context: YourContext,
baseUrl: 'https://your.api.domain'
}, {
CustomAPIs,
CustomUtils,
CustomLDK
})
```