diff --git a/src/getWoker.ts b/src/getWoker.ts new file mode 100644 index 0000000..e48b805 --- /dev/null +++ b/src/getWoker.ts @@ -0,0 +1,5 @@ +import { wrap } from 'comlink'; +import { Obj } from './webWorker'; + +const worker = new Worker(new URL('./webWorker.ts', import.meta.url)); +export const workerObj = wrap(worker); diff --git a/src/hook.ts b/src/hook.ts index ab005ab..0fb2c19 100644 --- a/src/hook.ts +++ b/src/hook.ts @@ -2,7 +2,7 @@ import { useEffect, useState } from 'react'; import * as mmdb from 'mmdb.js'; import { fetchFileAsBuffer } from './utils'; -const _mmdbUrl = +export const _mmdbUrl = 'https://raw.githubusercontent.com/Max-Sum/17mon-mmdb/release/Country.mmdb'; export const useIp = (mmdbUrl?: string) => { diff --git a/src/index.ts b/src/index.ts index 1146a6d..f02fecd 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1 +1,3 @@ export * from './hook'; +export * from './webWorker'; +export * from './getWoker'; diff --git a/src/ipBox.tsx b/src/ipBox.tsx index 449cb19..6f88704 100644 --- a/src/ipBox.tsx +++ b/src/ipBox.tsx @@ -1,4 +1,4 @@ -import { FC, useEffect } from 'react'; +import { FC, useEffect, useState } from 'react'; import { useIp } from './hook'; import { prettyPrintJson } from 'pretty-print-json'; import './box.css'; @@ -28,23 +28,15 @@ const obj = wrap(worker); export const IpBoxWebworker: FC = (props) => { const { ip } = props; - const reader = useIp(); - const data = reader?.get(ip); - const html = prettyPrintJson.toHtml(data); - + const [html, setHtml] = useState(''); useEffect(() => { - const func = async () => {}; - func(); - }, []); + obj.getIPInfo(ip).then((res) => { + setHtml(prettyPrintJson.toHtml(res)); + }); + }, [ip]); return ( -
{ - obj.inc(); - alert(`Counter: ${await obj.counter}`); - }} - > +
ip address:
{ip}

     
diff --git a/src/webWorker.ts b/src/webWorker.ts index cc34a28..412a09b 100644 --- a/src/webWorker.ts +++ b/src/webWorker.ts @@ -1,12 +1,27 @@ import { expose } from 'comlink'; +import { fetchFileAsBuffer } from './utils'; +import * as mmdb from 'mmdb.js'; +import { _mmdbUrl } from './hook'; + +let cache: mmdb.Reader | null = null; + +const getReader = async (url: string) => { + if (cache) return cache; + const res = await fetchFileAsBuffer(url); + if (!res) return; + const reader = new mmdb.Reader(res); + cache = reader; + return reader; +}; const obj = { - counter: 12, - inc() { - this.counter++; + getIPInfo: async (ip: string, url: string = _mmdbUrl) => { + const reader = await getReader(url); + return reader?.get(ip); }, }; expose(obj); export type Obj = typeof obj; +export type Reader = typeof cache;