swarpc - v0.14.0
    Preparing search index...

    Function Server

    • Internal

      Creates a sw&rpc server instance.

      Type Parameters

      Parameters

      • procedures: Procedures

        procedures the server will implement, see ProceduresMap

      • options: {
            scope?: WorkerGlobalScope;
            loglevel?: "debug" | "info" | "warn" | "error";
            _scopeType?: "dedicated" | "shared" | "service";
        } = {}

        various options

        • Optionalscope?: WorkerGlobalScope

          The worker scope to use, defaults to the self of the file where Server() is called.

        • Optionalloglevel?: "debug" | "info" | "warn" | "error"

          Maximum log level to use, defaults to "debug" (shows everything). "info" will not show debug messages, "warn" will only show warnings and errors, "error" will only show errors.

        • Optional_scopeType?: "dedicated" | "shared" | "service"

          Don't touch, this is used in testing environments because the mock is subpar. Manually overrides worker scope type detection.

      Returns SwarpcServer<Procedures>

      a SwarpcServer instance. Each property of the procedures map will be a method, that accepts a function implementing the procedure (see ProcedureImplementation). There is also .start(), to be called after implementing all procedures.

      An example of defining a server:

      import { Server } from "swarpc";
      import { procedures } from "./lib/procedures";

      // 1. Give yourself a server instance
      const swarpc = Server(procedures);

      // 2. Implement your procedures
      swarpc.multiply(async ({ a, b }, onProgress, { abortSignal, nodeId }) => {
      const updateProgress = (progress: number) =>
      onProgress({ progress, node: nodeId });

      abortSignal?.throwIfAborted();

      let result = 0;

      for (const i of Array.from({ length: b }).map((_, i) => i)) {
      result += a;
      updateProgress(i / b);
      await new Promise((r) => setTimeout(r, 500));
      abortSignal?.throwIfAborted();
      }

      updateProgress(1);

      return { result, node: nodeId };
      });

      // Start the server
      swarpc.start();