# How to separate service logic from its transport

> Move a service's business logic into a plain function over plain data, reduce each handler to an adapter, and test the logic with no broker or framework.

Source: https://voxgig.com/howto/separate-service-logic-from-the-transport

- Audience: library-maintainer
- Level: intermediate
- Languages: typescript, go
- Verified: 2026-11-30
- Published: 2026-11-30

## Short answer

Write the business logic as a function that takes an order and returns a quote or a refusal, all plain data, with no import from a transport or framework. Each transport gets an adapter that unpacks its input, calls the function, and packs the result into its own reply. Test the function with `node --test` or `go test` alone. Keep request ids and reply callbacks out of the signature.

---
## You will need

A service whose tests need a running broker, Node 22.18 or later, which runs `.ts` files by
[stripping the types](https://nodejs.org/api/typescript.html), and Go 1.24 or later for the Go half.
Verified 2026-11-30 against Node 22.23.5, Go 1.24.7 and 1.25.14, NestJS 12.6.3 and Moleculer
0.15.2. Moleculer 0.15.2 asks for Node 22 or later in its `engines` field.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Moleculer mixins](https://moleculer.services/docs/0.15/services.html) | Several Moleculer services share the logic, and the broker already carries your messages | Mixed-in methods merge into each service schema, and the action itself only runs inside a broker | One service uses the logic, or the code may leave Moleculer |
| [NestJS providers with dependency injection](https://docs.nestjs.com/providers) | A Nest service that serves HTTP and a Nest transport from one module | Decorators need a compile step, and code outside Nest reaches a provider through `app.get` | The service is small, or the logic must also run outside Nest |
| [ports and adapters with plain functions](https://alistair.cockburn.us/hexagonal-architecture) | Logic you test alone and serve over more than one transport | Each transport needs a hand-written adapter, and no container wires the dependencies for you | A framework already owns your wiring and its tests run fast enough |

All three ran the same `quoteShipping` function below. Ports and adapters cost an adapter per
transport and give a function any caller can use.[^1] A NestJS provider adds a hybrid application for
a second transport, with the price of a build step and a container. A Moleculer mixin
moves between brokers through the `transporter` option, and only inside Moleculer.

## Write the logic as a function over plain data

The function takes an order and returns a result. A refusal is a value rather than an exception or a
status code, so every adapter decides how its own transport says no.

```ts title="shipping.ts"
export function quoteShipping(order: Order): Result {
  if (order.lines.length === 0) return refuse('empty-order', 'an order needs at least one line')
  let grams = 0
  for (const line of order.lines) {
    if (!Number.isInteger(line.qty) || line.qty < 1 || !Number.isInteger(line.grams) || line.grams < 1) {
      return refuse('bad-line', `line ${line.sku} needs a positive whole qty and grams`)
    }
    grams += line.grams * line.qty
  }
  if (grams > MAX_GRAMS) return refuse('too-heavy', `${grams} g is over the ${MAX_GRAMS} g limit`)
  const band = bandFor(order.country)
  const steps = Math.ceil(grams / 500)
  const cents = BASE_CENTS[band] + PER_HALF_KILO_CENTS[band] * (steps - 1)
  return { ok: true, quote: { orderId: order.orderId, band, grams, cents } }
}
```

The tests call it with the [Node test runner](https://nodejs.org/api/test.html) and nothing else.
One reads the module's source and fails if it gains an `import`. The last one compiles
`signature.check.ts`, which fails to compile if `quoteShipping`, the NestJS provider, or the
Moleculer mixin gains a parameter, or if `Order` gains a field such as a request id.

```bash
node --test shipping.test.ts
```

```text output
# Subtest: no signature carries a transport concept, checked by the compiler
ok 5 - no signature carries a transport concept, checked by the compiler
  ---
  duration_ms: 623.370398
  type: 'test'
  ...
1..5
# tests 5
# suites 0
# pass 5
# fail 0
# cancelled 0
# skipped 0
# todo 0
```

The Go half has the same split. `QuoteShipping` returns a `Quote` and a `*Refusal`, and its table
test needs only the standard [`testing`](https://pkg.go.dev/testing) package. `TestSignatureIsPlain`
uses `reflect` to fail if the function or its types gain a parameter or a field. Go checks each
line's weight before multiplying, because two large `int` values overflow and wrap to a small one.

```bash
cd go && go test -v ./... | grep -E -e '--- (PASS|FAIL)' -e '^(PASS|FAIL)$' | sed -E 's/ \([0-9.]+s\)$//'
```

```text output
--- PASS: TestHTTPHandler
--- PASS: TestQuoteShipping
    --- PASS: TestQuoteShipping/domestic_1.2_kg
    --- PASS: TestQuoteShipping/eu_half_kilo
    --- PASS: TestQuoteShipping/world_half_kilo
    --- PASS: TestQuoteShipping/empty_order
    --- PASS: TestQuoteShipping/zero_qty
    --- PASS: TestQuoteShipping/too_heavy
    --- PASS: TestQuoteShipping/too_heavy_without_overflow
    --- PASS: TestQuoteShipping/thirty_kilos_exactly
--- PASS: TestSignatureIsPlain
PASS
```

`TestHTTPHandler` drives the Go adapter with [`httptest`](https://pkg.go.dev/net/http/httptest)'s
recorder, so it opens no socket either.

## Reduce each handler to an adapter

An adapter unpacks, calls, and packs. The message adapter carries the correlation id from the
request headers to the reply headers, and the function never sees it.

```ts title="adapters.ts"
export function messageAdapter(message: Envelope): Envelope {
  const reply = (status: string, body: unknown): Envelope => ({
    subject: `${message.subject}.reply`,
    data: JSON.stringify(body),
    headers: { 'request-id': message.headers['request-id'] ?? '', status },
  })
  const order = parseOrder(message.data)
  if (!order) return reply('invalid', { error: 'data is not an order' })
  const result: Result = quoteShipping(order)
  return result.ok ? reply('ok', result.quote) : reply('refused', { error: result.error })
}
```

One order, through the HTTP adapter on a loopback port and through the message adapter:

```bash
node demo.ts
```

```text output
http     200 {"orderId":"o-42","band":"eu","grams":1200,"cents":1400}
message  ok {"orderId":"o-42","band":"eu","grams":1200,"cents":1400} request-id=req-7
```

## Run the same function under NestJS and Moleculer

The NestJS provider wraps the function, and one controller serves it over HTTP and, as a
[hybrid application](https://docs.nestjs.com/faq/hybrid-application), over Nest's TCP transport.
Node's type stripping [does not transform decorators](https://nodejs.org/api/typescript.html), so
the Nest files compile with `tsc` first.

```bash
npx tsc -p . && node nest-build/nest/main.js
```

```text output
nest http     200 {"orderId":"o-42","band":"eu","grams":1200,"cents":1400}
nest tcp      {"orderId":"o-42","band":"eu","grams":1200,"cents":1400}
nest provider {"ok":true,"quote":{"orderId":"o-42","band":"eu","grams":1200,"cents":1400}}
```

The Moleculer mixin gives the function to the `shipping` service as a method. Two brokers join
through the `Fake` transporter, which moves packets on an in-process bus,[^2] and the second broker
calls the action on the first.

```bash
node moleculer-demo.ts
```

```text output
moleculer {"orderId":"o-42","band":"eu","grams":1200,"cents":1400}
moleculer refused: MoleculerClientError 422 empty-order from shipping-node
```

Three structures return one quote, because all three call one function.

## Check it worked

Run the adapter tests too. They post to the HTTP adapter, send an envelope with a request id, call
the Moleculer action across brokers, and check that the refusal maps to `422` in each.

```bash
node --test transports.test.ts
```

```text output
1..4
# tests 4
# suites 0
# pass 4
# fail 0
```

Change the EU base rate in `shipping.ts` and the logic test fails along with every adapter test. The
logic test runs first, and it starts no server.

## When it goes wrong

The function grows a transport parameter. Someone adds the request id for a log line and the reply
callback for convenience, and the next transport has to fake both.

```bash
node pitfall.ts
```

```text output
leaky, with the envelope it was written for    replies: 1
leaky, from an HTTP adapter with no meta       throws TypeError: Cannot read properties of undefined (reading 'requestId')
leaky, an empty order                          replies: 0
plain, an empty order                          returns {"ok":false,"error":{"code":"empty-order","message":"an order needs at least one line"}}
```

The leaky version also drops refusals: it returns without calling `reply`, so the caller waits for
an answer that never comes. Return refusals as data, and let the adapter put the request id in its
log line and its reply.

An adapter that only parses JSON lets `{}` or `null` through to a function typed for an `Order`.
The function then throws, and an exception from an `async` request listener ends the Node process.
Check the shape in the adapter with `toOrder` and answer with the transport's own error. The HTTP
adapter answers `400`, and `transports.test.ts` posts five bodies that are not orders to prove it.

## When not to do this

Do not split a handler whose logic is two lines of field copying. An adapter around a function
that does nothing doubles the code and tests the copy twice.

Do not wrap the function in a NestJS provider and then inject other providers into it. Once the
logic needs the container to construct it, its tests need the container as well.

Skip the separation when the service lives inside one framework for good and its tests already run
without a broker. Choose the plain function when a second transport is on the plan, or when another
team must call the logic as a library.

## Related how-tos

- [Split a monolith into message-based services with Seneca](/howto/split-a-monolith-into-message-based-services)

- [Override a service action without forking its plugin](/howto/override-a-service-action-without-forking)

- [Run one service locally and at the edge without forking it](/howto/run-one-service-locally-and-at-the-edge)

- [Evaluate message rules with json-rules-engine](/howto/evaluate-message-rules-with-json-rules-engine)

- [Add a repository layer between a service and its database](/howto/add-a-repository-layer-to-a-service)

## Last verified

Verified 2026-11-30 against Node 22.23.5, Go 1.24.7 and Go 1.25.14, NestJS 12.6.3, Moleculer
0.15.2, `rxjs` 7.8.2 and TypeScript 7.0.2. Every output block is what the preceding command printed.

[^1]: The idea has a paper, and the paper has a version number. Alistair Cockburn's
[Hexagonal (Ports and Adapters) Architecture](https://alistair.cockburn.us/hexagonal-architecture)
is HaT Technical Report 2005.02, dated 2005-09-04 and marked version 0.9, to be updated after reader
comments. Its first sentence asks for software that works without either a UI or a database,
so that automated regression tests can run against it, among two other reasons it gives.

[^2]: Moleculer's [networking page](https://moleculer.services/docs/0.15/networking.html) for
version 0.15 does not mention the `Fake` transporter. Its
[source](https://github.com/moleculerjs/moleculer/blob/v0.15.2/src/transporters/fake.js) puts an
event emitter on `global.bus`, with a comment that says the property exists to transfer messages
between brokers in the same process.