mirror of
https://github.com/BewlyBewly/BewlyBewly.git
synced 2025-04-14 13:15:29 +00:00
refactor: adjust the directory structure of messageListeners/ (#1066)
This commit is contained in:
51
src/utils/api.ts
Normal file
51
src/utils/api.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import type { API_COLLECTION } from '~/background/messageListeners/api'
|
||||
|
||||
type CamelCase<S extends string> = S extends `${infer P1}_${infer P2}${infer P3}`
|
||||
? `${Lowercase<P1>}${Uppercase<P2>}${CamelCase<P3>}`
|
||||
: Lowercase<S>
|
||||
|
||||
type APIFunction<T = typeof API_COLLECTION> = {
|
||||
[K in keyof T as CamelCase<string & K>]: {
|
||||
// @ts-expect-error allow params
|
||||
[P in keyof T[K]]: T[K][P] extends Function ? T[K][P] : Lowercase<T[K][P]['_fetch']['method']> extends 'get' ? (options?: Partial<T[K][P]['params']>) => Promise<any> : (options?: Partial<T[K][P]['params'] & T[K][P]['_fetch']['body']>) => Promise<any>
|
||||
}
|
||||
}
|
||||
|
||||
// eslint-disable-next-line ts/no-unsafe-declaration-merging
|
||||
export interface APIClient extends APIFunction<typeof API_COLLECTION> {
|
||||
|
||||
}
|
||||
|
||||
// eslint-disable-next-line ts/no-unsafe-declaration-merging
|
||||
export class APIClient {
|
||||
private readonly cache = new Map<string | symbol, any>()
|
||||
|
||||
constructor() {
|
||||
// @ts-expect-error ignore
|
||||
return new Proxy({}, {
|
||||
get: (_, namespace) => { // namespace
|
||||
if (this.cache.has(namespace)) {
|
||||
return this.cache.get(namespace)
|
||||
}
|
||||
else {
|
||||
const api = new Proxy({}, {
|
||||
get(_, p) {
|
||||
return (options?: object) => {
|
||||
return browser.runtime.sendMessage({
|
||||
contentScriptQuery: p,
|
||||
...options,
|
||||
})
|
||||
}
|
||||
},
|
||||
})
|
||||
this.cache.set(namespace, api)
|
||||
return api
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const api = new APIClient()
|
||||
|
||||
export default api
|
||||
10
src/utils/tab.ts
Normal file
10
src/utils/tab.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import browser from 'webextension-polyfill'
|
||||
|
||||
import { TAB_MESSAGE } from '~/background/messageListeners/tab'
|
||||
|
||||
export function openLinkInBackground(url: string) {
|
||||
return browser.runtime.sendMessage({
|
||||
contentScriptQuery: TAB_MESSAGE.OPEN_LINK_IN_BACKGROUND,
|
||||
url,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user