在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:ipfs-shipyard/service-worker-gateway开源软件地址:https://github.com/ipfs-shipyard/service-worker-gateway开源编程语言:JavaScript 95.8%开源软件介绍:service-worker-gateway
Lead MaintainerInstallation> npm i service-worker-gateway Testing the exampleRun the following commands: > git clone https://github.com/ipfs-shipyard/service-worker-gateway.git
> cd service-worker-gateway
> npm install
> cd example
> npm install
> npm run build
> npm run start UsageThe service worker gateway will get in action when specifc HTTP requests occur.
Service Worker running on IPFS nodeThe service worker code lives in The IPFS node is created when the service worker 'activate' event is fired: const IPFS = require('ipfs')
self.addEventListener('activate', () => {
// Node started
}) The service worker listens for 'fetch' events so that it can respond to certain requests: self.addEventListener('fetch', (event) => {
const path = event.request.url
if (!path.startsWith(self.location.origin + '/ipfs')) {
return console.info(`Fetch not in scope: ${path}`)
}
const regex = /^.+?(\/ipfs\/.+)$/g
const match = regex.exec(path)
const ipfsPath = match[1]
console.info(`Service worker trying to get ${ipfsPath}`)
event.respondWith(fetchFile(ipfsPath))
}) Finally, the IPFS node is exposed for use by web pages/apps. Service workers are permitted to talk to web pages via a messaging API so we can use const { createProxyServer } = require('ipfs-postmsg-proxy')
// Setup a proxy server that talks to our real IPFS node
createProxyServer(() => ipfs, { /* ...config... */ }) Application codeThe application code is responsible for registering the service worker and talk to the IPFS node that runs in it. It is important to do feature detect, in order to verify if the client's browser supports service workers, and then the service worker is ready for being registered. Example: if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker-bundle.js')
.then((reg) => console.log('Successful service worker register'))
.catch((err) => console.error('Failed service worker register', err))
} Once the service worker is registered, it is possible to start communicating with the IPFS node that is running. To do this, we create a "proxy client" which can talk to our "proxy server" over the messaging API: if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker-bundle.js')
.then(async () => {
ipfs = createProxyClient({ /* ...config... */ })
// Now use `ipfs` as usual! e.g.
const { agentVersion, id } = await ipfs.id()
})
} RelatedLicense |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论