logosmonn

Wrap what your core calls

Published by Simon Ingeson

A common reason I’ve seen for wrapping a third-party library is that you may want to swap it out later (I’ve been guilty of it too). However, I can’t remember the last time I actually did. I still prefer to wrap them though, because the swap wasn’t the point. The point was to decide what your own code is allowed to do.

As an example, I don’t wrap React. I do wrap Prisma. Both are third-party, and they’re all over the place in a typical TypeScript app, so the line between them needs a reason. My reason is to protect the core. Your core is the business logic that makes the product actually worth anything. Wrap what your core calls, and keep its callers boring.

React and Nest.js are examples of code that calls your code (I’ll refer to this as “framework” in this context). You give them your components and your handlers, and they decide when to invoke them. You can’t put anything in front of that, so that layer has to be as thin as possible. Let the framework handle rendering or routing, and pass the real work straight to your core. Prisma is a library, and it works the other way around. Your code calls it, and from the first call, Prisma’s types are already present in your business logic. Your core will never import React (unless your core is a React component library, where React is the point), but it will import Prisma the moment you allow it to.

Ports and adapters

One way to keep a library out of your core is ports and adapters. Your core defines a port, a small interface that says what it needs from the outside world in its own terms. An adapter then implements that port using whatever library actually does the work. Prisma lives in an adapter, and your core only ever sees the port.

In TypeScript, a port can be as small as a single function type. A use case (one piece of business logic, like renaming a user) asks for the ports it needs and nothing else.

type FindUserById = (id: UserId) => Promise<User | undefined>
type SaveUser = (user: User) => Promise<void>

async function renameUser(
  deps: { findUserById: FindUserById; saveUser: SaveUser },
  params: { id: UserId; name: UserName }
): Promise<void> {
  const user = await deps.findUserById(params.id)
  if (!user) throw new UserNotFoundError(params.id)
  await deps.saveUser({ ...user, name: params.name })
}

Nothing in there refers to Prisma.

So where does Prisma meet renameUser? In the glue code. That’s the thin layer where a framework passes you a request. A Nest.js controller, a GraphQL resolver, and a React server action all do the same thing. They parse the input, build the adapters, and then call the use case. Keep your logic in plain functions, and treat anything that touches a framework as glue.

const users = createPrismaUsers(prisma)
await renameUser(users, {
  id: parseUserId(input.id),
  name: parseUserName(input.name)
})

That’s dependency injection, done by hand. If you already use a container, like the one Nest.js ships with, it can do the wiring instead. Either way, the wiring lives in the glue.

What a port buys

The first thing a port buys is control. Prisma’s client can do pretty much anything to your database (any query, any filter, raw SQL). If you hand the client over to your business logic, then all of that is available everywhere. A port only gives you what you’ve decided to give. And since each use case lists its ports, it gets only the capabilities it asks for. renameUser can read a user and save a user, but it can’t delete one. Not “shouldn’t.” Can’t.

A port can also contain rules that the library itself doesn’t. Prisma’s update will happily overwrite a row someone else changed a second ago, since it doesn’t ask which version you read. So every mutable entity has a version, and only an adapter can create one.

type Version = number & { readonly __brand: 'Version' }
type User = { id: UserId; name: UserName; version: Version }

findUserById returns the user with its version. saveUser will only write if the stored row still has that version. If someone else got there first, the save fails, and the caller rereads and tries again. That’s optimistic concurrency control. renameUser hasn’t changed at all, and the check is no longer something anyone has to remember. A made-up number won’t get in either, since a plain 5 won’t type-check as a Version.

Ports also make testing cheap. renameUser needs two functions, so a test can pass it two functions.

const saved: User[] = []
await renameUser(
  {
    findUserById: async () => alice,
    saveUser: async (user) => {
      saved.push(user)
    }
  },
  { id: alice.id, name: newName }
)

No database, no Docker, no mocking library. For the tests that run a full flow, you write an in-memory adapter for each port (backed by a Map). Then you have a small number of integration tests that run each query against the real database, to prove that the Prisma adapter does what the port says it does. The logic runs in memory, only the queries hit the real database, and CI stays fast.

And the swap (the reason everyone gives) comes along for free. If you move off Prisma, you write a new adapter for each port and switch one port at a time, with the old adapter still running the rest.

You don’t even have to leave Prisma to need that. “Not found” is a case in point. Prisma 4 deprecated the rejectOnNotFound option in favor of findUniqueOrThrow. Prisma 5 removed the option and changed where you import some error classes from. Prisma 6 removed NotFoundError completely, and you now check for a PrismaClientKnownRequestError with code P2025. If your business logic is catching Prisma errors, you’ve got three rewrites of every not-found check. With a port, findUserById returns undefined, renameUser deals with it, and only the adapter changes, three times, in one place.

What it costs

None of this is free.

  • The lowest common denominator. A port hides Prisma’s sharp edges, and its best bits with them (relation loading, raw SQL, and so on). Every feature you want back is a hole you have to cut in the port.
  • N+1 queries. Load 100 posts in one query, then call findUserById for each post’s author, and that’s 101 queries. Ports end up needing batch versions (like findUsersByIds), so the database can influence the port design after all.
  • Drift. An in-memory adapter doesn’t enforce unique constraints, ordering, or the version check unless you make it. Run one contract test suite against both adapters, or the tests will go green while production disagrees.
  • No one knows your ports. A new hire will know Prisma, its docs, and its Stack Overflow answers. An agent has read a million Prisma examples and none of yours.

The biggest cost is transactions. Say you’re renaming a user and want to write an audit entry in the same transaction. With Prisma, that’s one $transaction call. With ports, saveUser and the audit write are two separate functions with absolutely no idea what the other is doing. My solution is to keep the transaction out of the use case. renameUser shouldn’t be aware of or care about whether it’s running in a transaction. That’s the job of the glue (the shell, in functional core, imperative shell terms). The glue opens the transaction, binds the adapters to it, and then passes them to the use case. Take that as far as your requirements call for, and no further.

When to skip it

At first glance, Zod looks like it breaks the rule. Your core calls it, so the rule says wrap it, but a port over Zod would just be Zod again. For me, validation belongs at the boundary, where the outside world feeds data into your system. The boundary parses the raw input into types like UserName, and the core never sees anything that isn’t valid. Your core doesn’t call Zod at all. The only way it gets back in is via z.infer<typeof User> as your domain type, which effectively imports Zod into the core one type at a time (this is why I prefer to keep domain types separate from the schemas).

Beyond frameworks and validation, I skip the port when:

  • The library is only used in one file. That file is the adapter.
  • The code is a prototype I fully expect to throw away.
  • A polyfill is filling a gap the platform will close. Once Temporal ships everywhere, a port over the polyfill is just something you delete.

All of that is what I’d do when building something from zero to one. In an established codebase, you go with the conventions already there. If you see the pain this post describes (Prisma errors caught in business logic, a database spun up to test a rename, and so on), you might well argue for ports and adapters and have an agent do the refactor. Whether that’s the right call is a business decision, not a technical one. An agent will make the refactor cheap to write, but the refactor still has to beat whatever else the team could have shipped that week.

Wrap what your core calls. Keep its callers boring.