Function: nwjsServiceEntrypoint()
说明
本页由源码中的注释生成,内容为英文。
nwjsServiceEntrypoint(
options?):EntrypointAdapter<ServiceContext<{ }>>
Create a service adapter of an entrypoint served to the windows of NW.js, in its Node.js context (the background script of the application). It puts a NwjsServiceBridge on the global object, which NW.js shares with the pages of its windows: the trusted page of a window holds the user interface in a <webview> (the interface has no Node.js), and forwards the messages of the interface to the bridge.
bridge.invoke(data, clientId) resolves to {success, error, payload} (see ServiceResponseCodec): payload is the result, or error the whole error object when the action failed (no matching action, validation…). Each page is a client, identified by the id it gives (a non-empty string of at most 200 characters), which its requests carry as ServiceContext.clientId; bridge.subscribe(clientId, push) registers it for the events pushed by Entrypoint.notify and Entrypoint.broadcast, and bridge.unsubscribe(clientId) removes it (its page loaded again, its window closed), aborting its requests in progress (their abort signal fires). A push that throws (its window is gone) removes its client.
When the entrypoint stops, the new invocations resolve to an EntrypointStoppedException error; once the requests in progress end, the bridge is removed.
Parameters
options?
The adapter options; by default the bridge is global[Symbol.for('lakutata:service')].
Returns
EntrypointAdapter<ServiceContext<{ }>>
The adapter, to give to the service option of buildEntrypoints.
Example
import {Application} from 'lakutata'
import {buildEntrypoints, Controller} from 'lakutata/com/entrypoint'
import {ServiceAction} from 'lakutata/decorator/ctrl'
import {nwjsServiceEntrypoint, type NwjsServiceBridge} from 'lakutata/adapter/nwjs'
class EchoController extends Controller {
@ServiceAction({cmd: 'echo'})
public async echo(input: {text: string}): Promise<string> {
return input.text
}
}
//In the background script of the application (its Node.js context)
Application.run({
id: 'desktop.app',
name: 'Desktop',
components: {
entrypoint: buildEntrypoints({
controllers: [EchoController],
service: nwjsServiceEntrypoint()
})
},
bootstrap: ['entrypoint']
})
//In the trusted page of a window, which shares the global object with the Node.js context
declare const global: Record<symbol, NwjsServiceBridge>
const bridge: NwjsServiceBridge = global[Symbol.for('lakutata:service')]
const clientId: string = crypto.randomUUID()
//The events pushed by entrypoint.notify(clientId, 'progress', 50)
bridge.subscribe(clientId, (name: string, args: unknown[]): void => console.log(name, ...args))
//{success: true, error: null, payload: 'hi'}
console.log(await bridge.invoke({cmd: 'echo', text: 'hi'}, clientId))