Commit 4f231921 authored by 郑磊's avatar 郑磊

init

parents
/// <reference types="vite/client" />
const variables = {
...import.meta.env,
}
const injected: Record<string, any> = {
platform: 'web',
}
/**
* 获取或设置环境变量
* @param name
* @returns
*/
export function env(name: string, value?: any) {
if (typeof value !== 'undefined') {
injected[name] = value
}
return injected[name] ?? variables[name]
}
import axios from 'axios'
import { http } from '../common/http'
http.defaults.adapter = axios.getAdapter('xhr')
export { http }
export * from './http'
export * from './storage'
export * from './security'
export { default as WebSocket } from './ws'
export * from './env'
console.log('Ball Web Environment Loaded')
export { default as md5 } from 'md5'
/**
* 读取本地缓存数据
*/
export async function getStorage(key: string, defaultValue?: any) {
const data = localStorage.getItem(key)
if (typeof data !== 'string' || data === '') {
return defaultValue
}
try {
return JSON.parse(data)
} catch {
return defaultValue
}
}
/**
* 读取所有的本地缓存数据
*/
export async function getAllStorage() {
if (localStorage.length === 0) return {}
const result: Record<string, any> = {}
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i)!
result[key] = getStorage(key)
}
return result
}
/**
* 设置本地缓存数据
*/
export async function setStorage(key: string, value: any) {
if (typeof value === 'undefined' || value === null) {
return removeStorage(key)
}
if (typeof value === 'bigint' || typeof value === 'function' || typeof value === 'symbol') {
return
}
localStorage.setItem(key, JSON.stringify(value))
}
/**
* 删除本地缓存数据
*/
export async function removeStorage(key: string) {
localStorage.removeItem(key)
}
export default WebSocket
import axios from 'axios'
/**
* 创建用于执行http请求的axios实例
*/
export const http = axios.create()
import { app } from 'electron'
const variables = {
...process.env,
}
const injected: Record<string, any> = {}
injected.platform = process.platform
injected.arch = process.arch
injected.build_number = 1
injected.version = app.getVersion()
injected.package = 'vip.188zq.desktop'
process.env.INJECTED = JSON.stringify(injected)
/**
* 设置环境变量
* @param name 环境变量名
* @param value 环境变量值
*/
export function env(name: string, value: string): void
/**
* 读取环境变量
* @param name
*/
export function env(name: string): string | undefined
export function env(name: string, value?: string) {
if (typeof value === 'string') {
injected[name] = value
process.env.INJECTED = JSON.stringify(injected)
}
return injected[name] ?? variables[name]
}
import axios from 'axios'
import { http } from '../../common/http'
http.defaults.adapter = axios.getAdapter('http')
export { http }
export { WebSocket } from 'ws'
export * from './http'
export * from './security'
export * from './storage'
export * from './env'
console.log('Electron Main Module Loaded')
import { createHash } from 'node:crypto'
/**
* 计算输入值的md5
* @param input
*/
export function md5(input: string): string {
return createHash('md5').update(input, 'utf-8').digest('hex').toLowerCase()
}
import { BrowserWindow, ipcMain } from 'electron'
import StoreModule from 'electron-store'
const Store: typeof StoreModule =
// @ts-ignore
typeof StoreModule === 'function' ? StoreModule : StoreModule.default
const rawStore = new Store()
/**
* 读取本地缓存数据
*/
export function getStorage(key: string, defaultValue?: any) {
return Promise.resolve(rawStore.get(key, defaultValue))
}
/**
* 读取所有的本地缓存数据
*/
export function getAllStorage() {
return Promise.resolve(rawStore.store)
}
/**
* 设置本地缓存数据
*/
export async function setStorage(key: string, value: any) {
rawStore.set(key, value)
BrowserWindow.getAllWindows().forEach((window) => {
window.webContents.send('store:set', key, value)
})
return Promise.resolve()
}
/**
* 删除本地缓存数据
*/
export function removeStorage(key: string) {
rawStore.delete(key)
BrowserWindow.getAllWindows().forEach((window) => {
window.webContents.send('store:delete', key)
})
return Promise.resolve()
}
ipcMain.on('store:set', (event, name: string, value: any) => {
rawStore.set(name, value)
const id = event.sender.id
BrowserWindow.getAllWindows().forEach((window) => {
if (window.webContents.id === id) return
window.webContents.send('store:set', name, value)
})
})
ipcMain.on('store:delete', (event, name: string) => {
rawStore.delete(name)
const id = event.sender.id
BrowserWindow.getAllWindows().forEach((window) => {
if (window.webContents.id === id) return
window.webContents.send('store:delete', name)
})
})
ipcMain.handle('store:init', () => rawStore.store)
const injected = process.env.INJECTED ? JSON.parse(process.env.INJECTED) : {}
export function env(name: string) {
return injected[name] ?? process.env[name]
}
export { default as WebSocket } from '../../browser/ws'
export * from '../../browser/http'
export * from '../../browser/security'
export * from './env'
export * from './storage'
console.log('Electron Renderer Module Loaded')
import { ElectronAPI } from '@electron-toolkit/preload'
declare global {
interface Window {
ipcRenderer: ElectronAPI['ipcRenderer']
process: ElectronAPI['process']
}
const ipcRenderer: ElectronAPI['ipcRenderer']
const process: ElectronAPI['process']
}
const rawStore: Record<string, any> = {}
const readyPromise = new Promise<void>((resolve) => {
ipcRenderer.invoke('store:init').then((data: Record<string, any>) => {
Object.assign(rawStore, data)
resolve()
})
})
/**
* 读取本地缓存数据
* @param key 缓存键名
* @param defaultValue 读取失败时的默认值
*/
export async function getStorage(key: string, defaultValue?: any) {
await readyPromise
return rawStore[key] ?? defaultValue
}
/**
* 读取所有的本地缓存数据
*/
export async function getAllStorage() {
await readyPromise
return { ...rawStore }
}
/**
* 写入本地缓存数据
* @param key 缓存键名
* @param value 要写入的数据
*/
export async function setStorage(key: string, value: any) {
await readyPromise
rawStore[key] = value
ipcRenderer.send('store:set', key, value)
}
/**
* 删除本地缓存数据
* @param key 缓存键名
*/
export async function removeStorage(key: string) {
await readyPromise
delete rawStore[key]
ipcRenderer.send('store:delete', key)
}
import { AxiosInstance } from 'axios'
/**
* 读取本地缓存数据
* @param key 缓存键名
* @param defaultValue 读取失败时的默认值
*/
export function getStorage<T>(key: string, defaultValue: T): Promise<T>
/**
* 读取本地缓存数据
* @param key 缓存键名
*/
export function getStorage<T>(key: string): Promise<T | undefined>
/**
* 读取所有的本地缓存数据
*/
export function getAllStorage(): Promise<Record<string, any>>
/**
* 写入本地缓存数据
* @param key 缓存键名
* @param value 要写入的数据
*/
export function setStorage(key: string, value: any): Promise<void>
/**
* 删除本地缓存数据
* @param key 缓存键名
*/
export function removeStorage(key: string): Promise<void>
/**
* 执行HTTP请求的axios实例
*/
export const http: AxiosInstance
/**
* 计算输入值的md5
* @param input
*/
export function md5(input: string): string
export { WebSocket }
/**
* 设置环境变量
* @param name
* @param value
*/
export function env(name: string, value: string): void
/**
* 读取环境变量
* @param name
*/
export function env(name: string): string | undefined
import { env } from '../browser/env'
env('platform', 'miniapp')
export * from '../browser/env'
import { AxiosError } from 'axios'
import URL from 'core-js-pure/features/url'
import URLSearchParams from 'core-js-pure/features/url-search-params'
import { http } from '../common/http'
http.defaults.adapter = (config) => {
const url = new URL(config.url!, config.baseURL)
if (config.params) {
const params = new URLSearchParams(config.params)
params.forEach((value, name) => url.searchParams.append(name, value))
}
let dataType: string, responseType: string
switch (config.responseType) {
case 'arraybuffer':
dataType = '其他'
responseType = 'arraybuffer'
break
case 'text':
dataType = '其他'
responseType = 'text'
break
default:
dataType = 'json'
responseType = 'text'
break
}
return new Promise((resolve, reject) => {
const task = uni.request({
url: url.href,
method: config.method as any,
header: config.headers,
dataType,
responseType,
timeout: config.timeout,
success: (resp) => {
if (typeof config.validateStatus === 'function') {
if (!config.validateStatus(resp.statusCode)) {
reject(new AxiosError(`status code ${resp.statusCode}`))
return
}
}
resolve({
status: resp.statusCode,
statusText: 'ok',
data: resp.data,
headers: resp.header,
config,
})
},
fail: reject,
})
if (config.signal) {
config.signal.addEventListener!('abort', () => task.abort())
}
if (config.cancelToken) {
config.cancelToken.promise.then(() => task.abort())
}
})
}
export { http }
export * from './env'
export * from './http'
export * from './storage'
declare module 'core-js-pure/features/url' {
export default URL
}
declare module 'core-js-pure/features/url-search-params' {
export default URLSearchParams
}
/**
* 读取本地缓存数据
*/
export function getStorage(key: string, defaultValue?: any) {
return new Promise<any>((resolve, reject) => {
uni.getStorage({
key,
success: (res) => {
if (typeof res.data === 'string' && res.data) {
try {
resolve(JSON.parse(res.data))
} catch {
resolve(defaultValue)
}
} else {
resolve(defaultValue)
}
},
fail: reject,
})
})
}
/**
* 读取所有的本地缓存数据
*/
export function getAllStorage() {
return new Promise<Record<string, any>>((resolve, reject) => {
uni.getStorageInfo({
success: (res) => {
if (res.keys.length === 0) {
resolve({})
return
}
Promise.all(res.keys.map(async (key) => [key, await getStorage(key)]))
.then((result) => {
resolve(Object.entries(result))
})
.catch(reject)
},
fail: reject,
})
})
}
/**
* 设置本地缓存数据
*/
export async function setStorage(key: string, value: any) {
if (typeof value === 'undefined' || value === null) {
return removeStorage(key)
}
if (typeof value === 'bigint' || typeof value === 'function' || typeof value === 'symbol') {
return
}
return new Promise<void>((resolve, reject) => {
uni.setStorage({
key,
data: JSON.stringify(value),
success: resolve,
fail: reject,
})
})
}
/**
* 删除本地缓存数据
*/
export function removeStorage(key: string) {
return new Promise<void>((resolve, reject) => {
uni.removeStorage({
key,
success: resolve,
fail: reject,
})
})
}
{
"compilerOptions": {
"lib": ["esnext", "dom"],
"types": ["@dcloudio/types"]
}
}
{
"name": "@ball/shared",
"description": "BallPredictAI多端兼容库",
"private": true,
"version": "1.0.0",
"react-native": "react-native/index.ts",
"typings": "index.d.ts",
"electron-main": "electron/main/index.ts",
"electron-renderer": "electron/renderer/index.ts",
"optionalDependencies": {
"@react-native-async-storage/async-storage": "^2.2.0"
},
"devDependencies": {
"@dcloudio/types": "^3.4.28",
"@types/crypto-js": "^4.2.2",
"@types/md5": "^2.3.6",
"electron-store": "^11.0.2"
},
"dependencies": {
"axios": "^1.13.2",
"core-js-pure": "^3.47.0",
"crypto-js": "^4.2.0",
"isomorphic-ws": "^5.0.0",
"md5": "^2.3.0",
"ws": "^8.18.3"
}
}
import { NativeModules, Platform } from 'react-native'
import { getBuildNumber, getBundleId, getVersion } from 'react-native-device-info'
const variables = NativeModules.Env.getConstants()
//基于RN的环境变量
variables.platform = Platform.OS
variables.version = getVersion()
variables.build_number = getBuildNumber()
variables.package = getBundleId()
/**
* 设置环境变量
* @param name 环境变量名
* @param value 环境变量值
*/
export function env(name: string, value: string): void
/**
* 读取环境变量
* @param name
*/
export function env(name: string): string | undefined
export function env(name: string, value?: string) {
if (typeof value === 'string') {
variables[name] = value
}
return variables[name]
}
import axios from 'axios'
import { http } from '../common/http'
http.defaults.adapter = axios.getAdapter('fetch')
export { http }
export * from '../browser/security'
export * from './env'
export * from './http'
export * from './storage'
export { default as WebSocket } from './ws'
console.log('ReactNative Module Loaded')
import AsyncStorage from '@react-native-async-storage/async-storage'
/**
* 读取本地缓存数据
*/
export async function getStorage(key: string, defaultValue?: any) {
const data = await AsyncStorage.getItem(key)
if (typeof data !== 'string' || data === '') {
return defaultValue
}
try {
return JSON.parse(data)
} catch {
return defaultValue
}
}
/**
* 读取所有的本地缓存数据
*/
export async function getAllStorage() {
const keys = await AsyncStorage.getAllKeys()
if (keys.length === 0) return {}
const data = await AsyncStorage.multiGet(keys)
return Object.fromEntries(
data.map(([name, value]) => [
name,
typeof value === 'string' && value !== '' ? JSON.parse(value) : undefined,
]),
)
}
/**
* 设置本地缓存数据
*/
export async function setStorage(key: string, value: any) {
if (typeof value === 'undefined' || value === null) {
return removeStorage(key)
}
if (typeof value === 'bigint' || typeof value === 'function' || typeof value === 'symbol') {
return
}
return AsyncStorage.setItem(key, JSON.stringify(value))
}
/**
* 删除本地缓存数据
*/
export function removeStorage(key: string) {
return AsyncStorage.removeItem(key)
}
export default WebSocket
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"lib": ["esnext", "dom"],
"moduleResolution": "bundler",
"noEmit": true,
"isolatedModules": true,
"strict": true,
"allowImportingTsExtensions": true,
"allowArbitraryExtensions": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment