Skip to content

Documentation / @andrew_l/service-actor / serviceActor

Function: serviceActor() ​

serviceActor<T>(factory?): object

Create service actor hooks

Type Parameters ​

T ​

T extends Record<PropertyKey, any> = { }

Parameters ​

factory? ​

() => T

Returns ​

inject() ​

inject: () => undefined | ServiceActor<T>

Returns the service actor instance from the current context.

Returns ​

undefined | ServiceActor<T>

use() ​

use: () => ServiceActor<T>

Returns the service actor instance from the context, or creates and binds a new instance if none exists.

Returns ​

ServiceActor<T>

with() ​

with: <Fn>(fn, params?) => Fn

Wrap a function to execute it with service actor providers

Type Parameters ​

Fn ​

Fn extends AnyFunction

Parameters ​

fn ​

Fn

params? ​

Partial<ServiceActor<T>>

Returns ​

Fn

Example ​

ts
const { use: useServiceActor, with: withServiceActor } = serviceActor(() => ({
  actorType: 'http-request',
  ipAddress: '',
 }));

app.use((ctx, next) => {
  return withServiceActor(
    {
      traceId: ctx.headers['x-request-id'],
      ipAddress: ctx.headers['x-forwarded-for'],
    },
    next,
  );
});

app.get('/', () => {
  const actor = useServiceActor();

  // { traceId: 'req_35123', actorId: null, actorType: 'http-request', ipAddress: '::' }
  console.log(actor);
});