<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by DT on Medium]]></title>
        <description><![CDATA[Stories by DT on Medium]]></description>
        <link>https://medium.com/@ivibe?source=rss-d2e051ee0d80------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*hmK3bgrQmuSWalPP.jpg</url>
            <title>Stories by DT on Medium</title>
            <link>https://medium.com/@ivibe?source=rss-d2e051ee0d80------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 22:19:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ivibe/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How Generated Prisma APIs Fail Before, During, and After a Query]]></title>
            <link>https://ivibe.medium.com/how-generated-prisma-apis-fail-before-during-and-after-a-query-ef30de0be0f8?source=rss-d2e051ee0d80------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef30de0be0f8</guid>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[DT]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 03:53:50 GMT</pubDate>
            <atom:updated>2026-08-18T03:53:50.143Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Start diagnosis by locating the phase that owns the failure.</em></p><p>Generated APIs fail in more than one place.</p><p>Scope note: these failure phases come from project documentation and pinned reproductions. They are not statistics from a large installed user base.</p><p>A router can reject its configuration before serving traffic. A guard can reject a shape when it is constructed. Caller routing can fail before a variant hook. Request validation can reject one body. A scoped operation can fail because trusted context is missing.</p><p>Then there is the harder category: the request succeeds, but the emitted Prisma arguments or response semantics differ from what the application assumed.</p><p>Those categories need different fixes and different tests. Searching an entire error string is less useful than asking when the behavior appeared and which layer can observe it.</p><h3>Start with a phase map</h3><p>A generated Prisma request crosses several boundaries:</p><pre>router construction<br>  caller resolution<br>    operation before-hooks<br>      variant before-hooks<br>        guard shape construction<br>          request validation<br>            Prisma argument execution<br>              response transport</pre><p>The exact ordering of shape work can depend on whether a shape is static or context-dependent, but the diagnostic split remains useful.</p><p>Startup failures implicate route descriptors. Caller failures implicate variant selection. Invalid query and Invalid data failures implicate the relationship between body and shape. Policy failures implicate trusted context. Successful-but-surprising results require inspection below the status code.</p><p>Error text is version-specific. The guard lab behind these examples pins prisma-guard 1.33.0, Zod 4.4.3, and Prisma 6.19.3. The HTTP read lab pins prisma-generator-express 1.64.4, Node 22.14.0, and PostgreSQL 16.6.</p><p>Treat exact strings as evidence for that version. Treat phase and cause as the durable debugging model.</p><h3>Before a request: configuration cannot form a contract</h3><p>Router construction validates operation descriptors.</p><p>An operation cannot configure both shape and variants. A variant map cannot be empty. Every variant descriptor needs a shape. Reserved shape keys cannot masquerade as caller names.</p><p>These are deployment-time faults. Catching them and continuing with a partially configured router would erase the boundary the application meant to expose.</p><p>An operation with neither shape nor variants is different: it is valid and calls Prisma without guard enforcement. That should be an explicit decision in route review.</p><p>Shape construction has its own failures. Empty combinators, empty projections, conflicting forced predicates, incomplete create shapes, invalid upsert structure, and bulk methods without a where shape are rejected before client data can make them safe.</p><p>A minimal reproduction should separate shape from transport:</p><pre>const query = guard.query(&#39;Plant&#39;, &#39;findMany&#39;, {<br>  where: {<br>    name: { contains: true },<br>  },<br>  take: { max: 50, default: 20 },<br>})</pre><pre>const args = query.parse({<br>  where: {<br>    name: { contains: &#39;fern&#39; },<br>  },<br>})</pre><p>This path is useful for read filtering, ordering, pagination arguments, and many shape-construction errors. It does not execute Prisma, apply delegate-time read projection, or represent mutation behavior.</p><p>The correction belongs in server configuration. Changing the request cannot repair a shape that is structurally unsafe.</p><h3>Before the handler: caller selection failed</h3><p>Named shapes and variants add a routing phase before the generated handler.</p><p>A missing caller fails when the map has no default. An unknown caller fails when no exact key, parameterized pattern, or default matches. Overlapping parameter patterns fail as ambiguous rather than depending on declaration order.</p><p>Caller data is passed separately from the Prisma body. Putting it inside request arguments is rejected.</p><p>For public contracts, a header may be an intentional selector. Privileged variants should come from authenticated resolveVariant logic. A custom header name does not make client input trusted.</p><p>Routing failure occurs after operation before-hooks and before variant hooks. That detail explains why operation-wide authentication can run even when no variant matches, while caller-specific hooks do not.</p><p>The fix is not always “add default.” A default accepts missing, blank, and unmatched callers. Add it only when that fallback contract is valid for every one of those cases.</p><h3>During validation: the request exceeded its declared boundary</h3><p>The verified read errors below identify the exact argument path.</p><p>An unrecognized where field is absent from the filter shape. An unrecognized select field attempts to widen the projection. A rejected skip was not enabled. A take error can mean the value exceeded its maximum or arrived as the wrong scalar type.</p><p>Generated GET helpers matter because Prisma-shaped arguments do not all coerce identically from hand-built query strings. Numeric filter values and dates can coerce in supported positions, while Boolean strings and pagination strings can fail. Use the generated encoder for GET or native JSON with the POST read twin.</p><p>Write validation follows method-specific Prisma structure. Create receives data. Update receives where and data. Upsert receives where, create, and update. Guarded batch create expects an array.</p><p>Bulk operations fail at two levels. Missing where in the shape is a construction problem. A runtime body that resolves to no client condition is a request problem.</p><p>Policy errors are separate again. Missing scope roots or missing context for a context-dependent shape indicate absent trusted state. Keeping missing-scope behavior in error mode prevents a missing context from becoming an unfiltered top-level query.</p><p>The useful debugging habit is to preserve the path. “400 from guard” is broad. “Read body attempted include.plants.take above its nested maximum” points to one contract node.</p><h3>After validation: success can still violate an assumption</h3><p>HTTP 200 proves that the route completed. It does not prove the client controlled the value it sent, the condition stayed in the branch where it was written, or the response projection used the expected default.</p><p>A wholly forced top-level predicate silently replaces client input. If a shape pins isPublished = true, a client can send false and still receive success while the emitted query keeps true.</p><p>Other forced positions are strict and reject client input. That asymmetry is why tests should assert argument ownership rather than generalize from one use of force().</p><p>Forced conditions inside OR are lifted into mandatory top-level constraints. A shape that appears to describe “client branch OR server branch” can execute as the client expression AND the forced predicate. Genuine server-owned disjunction needs a purpose-built query or database policy.</p><p>Projection adds another silent split. Guarded reads apply their shape projection when clients omit one, but that default appears at delegate execution rather than guard.query().parse().</p><p>Mutations behave differently. Without enforceProjection, an omitted client projection emits no mutation select, so normal Prisma no-projection behavior applies.</p><p>Nested scope is also easy to overread. Automatic scope intercepts supported top-level operations. It does not recursively filter relations loaded inside a projection. Scope roots are not filtered by their own root marker, and raw SQL bypasses the extension.</p><p>None of those behaviors can be diagnosed from status alone.</p><h3>Choose the read path before interpreting the response</h3><p>The generated surface has three separate read-delivery mechanisms: pagination, POST transport, and Express SSE.</p><p>findManyPaginated returns a defined outer contract:</p><pre>type PaginatedResult&lt;T&gt; = {<br>  data: T[]<br>  total: number<br>  hasMore: boolean<br>}</pre><p>hasMore is reliable for forward offset pagination with positive take. Cursor and negative-take requests can receive a Boolean without widening that documented guarantee. take: 0 produces no rows and false continuation while retaining the total.</p><p>The total has its own path. Distinct counting is subject to a configured limit. A materialized count source is used only for an unfiltered, unguarded, non-distinct request. Dynamic filtering, distinct, or a guard shape causes fallback to a compatible live count path.</p><p>That fallback can keep the answer correct while changing its cost and freshness source. Diagnose total semantics separately from row slicing.</p><p>POST reads solve transport size and encoding, not query power:</p><pre>POST /delivery/paginated<br>Content-Type: application/json</pre><pre>{&quot;where&quot;:{&quot;city&quot;:{&quot;equals&quot;:&quot;Bangkok&quot;}},&quot;take&quot;:20,&quot;skip&quot;:0}</pre><p>Send native JSON. The equivalent GET and POST route should share one guard contract. Request-body rewriting in a hook can break that equivalence because GET consumes parsed query parameters instead.</p><p>SSE changes delivery timing. It is useful only when the client implements progressive events, terminal success, terminal failure, and fallback.</p><pre>{&quot;type&quot;:&quot;progress&quot;,&quot;stage&quot;:&quot;relations&quot;}<br>{&quot;type&quot;:&quot;field&quot;,&quot;field&quot;:&quot;summary&quot;,&quot;data&quot;:{&quot;total&quot;:6}}<br>{&quot;type&quot;:&quot;result&quot;,&quot;data&quot;:{&quot;summary&quot;:{&quot;total&quot;:6},&quot;deliveries&quot;:[]}}</pre><p>Manual SSE stages are application-owned queries and need explicit guard treatment. Auto-include supports documented relation shapes within planner limits; unsupported plans follow configured fallback. Generated after-hooks are not guaranteed SSE cleanup handlers.</p><p>A successful read can therefore be wrong at several layers: unreliable continuation assumption, misunderstood count source, transport-specific hook behavior, or unguarded stage query.</p><h3>Match each claim to its test target</h3><p>One end-to-end request cannot prove every layer.</p><p>Use the parser for read-body validation and forced-merge structure. Use the guarded delegate when the claim concerns execute-time projection or mutation arguments. Use the extension operation path for automatic scope injection.</p><p>An isolated argument-capture harness can expose final mutation arguments without a database. It must wire the guard extension to an argument-returning model delegate; declaring a separate fake object without connecting it proves nothing. That harness establishes emitted arguments, not returned database rows.</p><p>Use database-backed fixtures when the claim concerns tenant outcomes, relation ownership, transactions, distinct totals, or provider behavior. Seed at least two tenants with discriminating rows.</p><p>Use HTTP tests for generated routing, serialization, hooks, POST equivalence, pagination responses, and SSE events.</p><p>Keep guard-enabled contract tests when browser E2E uses a mode that drops guard validation. A passing browser flow cannot prove a production rejection when the test environment removed the enforcing layer.</p><p>Keep each regression test at the lowest layer that can prove its claim. Smaller targets make later failures identify their owning phase instead of reopening the entire request path.</p><h3>Diagnose in one direction</h3><p>A compact sequence avoids random fixes:</p><ol><li>Determine startup failure, request failure, or successful surprise.</li><li>Identify router, caller, shape, policy, Prisma execution, or transport phase.</li><li>Reduce to one operation, one shape, and one body.</li><li>Inspect the argument at the closest available layer.</li><li>Add database or HTTP execution only when the claim requires it.</li><li>Compare exact messages only against the pinned dependency version.</li></ol><p>Generated APIs are easier to debug when their phases remain separate. Configuration errors should fail before traffic. Request violations should name the contract path. Successful responses should be verified against emitted arguments and documented transport semantics, not status alone.</p><p>The complete error index, silent-behavior evidence, read-path matrices, and reproducible labs live in the <a href="https://multipliedtwice.github.io/prisma-generator-express/">deeper Field Guide</a>.</p><p>Disclosure: This essay was AI-assisted and verified by the prisma-generator-express maintainer against the project sources and pinned labs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef30de0be0f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Define Every Prisma Endpoint’s Inputs and Outputs in One Place]]></title>
            <link>https://ivibe.medium.com/a-prisma-query-shape-is-an-api-contract-2369e3ff103b?source=rss-d2e051ee0d80------2</link>
            <guid isPermaLink="false">https://medium.com/p/2369e3ff103b</guid>
            <category><![CDATA[data-validation]]></category>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[api-design]]></category>
            <dc:creator><![CDATA[DT]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 21:52:26 GMT</pubDate>
            <atom:updated>2026-08-18T03:52:49.624Z</atom:updated>
            <content:encoded><![CDATA[<p>Use one guard configuration to control client values, filters, returned fields, and writes.</p><p>Prisma gives applications a rich argument language. That is excellent inside trusted server code. It becomes a product decision when the same argument structure crosses an HTTP boundary.</p><p>Which fields may a caller write? Which filters may it choose? Which values must the server pin? Which relations may leave the database? How many child rows can one response expand into?</p><p>prisma-guard shapes answer those questions beside the Prisma operation. The value is not validation alone. A shape is a compact API contract for control, filtering, projection, and mutation behavior.</p><p>That contract keeps repeated boundary work in one place. A generated operation can use the shape instead of rebuilding input schemas and field allowlists in every handler. The tradeoff is precision: a shape must describe what the library actually enforces, including the places where top-level scope does not reach.</p><p>Evidence note: this is maintainer-written guidance for the implementation as tested today. It does not summarize an established community convention.</p><p>Three review questions keep that precision manageable.</p><h3>Question one: who chooses each value?</h3><p>Every leaf in a shape assigns ownership.</p><pre>const values = {<br>  clientChooses: true,<br>  serverChooses: &#39;published&#39;,<br>  serverChoosesTrue: force(true),<br>  clientChoosesWithinRule: (base) =&gt; base.min(1).max(120),<br>}</pre><p>Bare true is not the Boolean value true. It is the sentinel for client control. A literal is server-owned. force(value) is also server-owned and is necessary when the literal itself is true. A refinement function leaves control with the client while replacing the field’s generated Zod chain with an inline rule.</p><p>This vocabulary is small. Position creates the surprising behavior.</p><p>In a where shape, forced scalar values belong inside an operator:</p><pre>const eventShape = {<br>  where: {<br>    isPublished: { equals: force(true) },<br>    title: { contains: true },<br>  },<br>}</pre><p>A wholly forced scalar predicate at the top level of where is lenient about client input. If the client sends the same value, a conflicting value, or another operator on that field, the server-owned predicate wins. The request does not fail merely because the client mentioned it.</p><p>That is not default behavior. A default yields to a supplied value. A force does not.</p><p>Other positions are strict. A forced modifier beside a client-controlled operator, a forced field inside a relation filter, a forced nested-include filter, or a forced mutation data field is removed from the client-facing schema. Sending that key produces a validation error even when the value matches.</p><p>The difference affects client design. A client may have to omit a server-owned write field entirely. Correcting it to the server value is still incorrect because ownership, not equality, controls acceptance.</p><p>Zod defaults and catches need the same ownership review. On a client-controlled field, omission behavior stays available and a catch may replace invalid input instead of rejecting it. On create, a generated default or catch directive can also satisfy completeness for a field omitted from the shape; its result is then injected as a server-owned value. Placement therefore changes ownership. Use substitution only when it is part of the API contract.</p><p>Refinement functions also replace the generated validation chain at that node. They should preserve every rule the endpoint still needs, not merely add one convenient minimum or maximum. This matters for values whose Prisma type alone is weaker than the product contract.</p><p>Forced update data also executes on every matching call. If an update shape forces status: &#39;active&#39;, changing an unrelated field through that shape also writes the status. Omit a field when the operation must not change it.</p><p>Boolean structure adds another ownership rule. A forced condition written inside OR is lifted into a mandatory top-level constraint. It cannot express a genuine server-owned disjunction such as “owned by this account OR shared with this group.” That policy needs a server-authored query, one suitable scoping column, or database enforcement.</p><p>The first review question is therefore more specific than “is this validated?” Ask who chooses the value, where the force sits, and what argument tree reaches Prisma.</p><h3>Question two: which data can leave the response?</h3><p>Filtering and projection solve different problems. A tenant filter chooses eligible records. A projection chooses fields and relations returned from those records.</p><p>On guarded reads, a shape-level select or include is both a whitelist and a default. A client can narrow within the declared tree. It cannot request a field outside it. If it sends no projection, guarded execution applies the shaped projection.</p><pre>const ticketShape = {<br>  where: {<br>    id: { equals: true },<br>  },<br>  select: {<br>    id: true,<br>    subject: true,<br>    description: true,<br>    customerNotes: {<br>      where: {<br>        accountId: { equals: force(accountId) },<br>      },<br>      select: {<br>        id: true,<br>        body: true,<br>      },<br>      take: { max: 20, default: 10 },<br>    },<br>  },<br>}</pre><p>This tree does four jobs. It keeps unlisted root fields closed. It limits note fields. It adds a mandatory relation condition. It bounds relation cardinality.</p><p>Nested relations need that explicit treatment because automatic tenant scope intercepts supported top-level operations. It does not recursively add predicates to relations loaded by select or include.</p><p>To-many relations can carry a nested where, projection, and bound. Sensitive to-one relations cannot carry a nested Prisma where. They must be omitted, reduced to safe scalar fields, queried through another guarded top-level operation, or protected by a database policy.</p><p>Choose projection style based on maintenance behavior. select keeps newly added fields closed until reviewed. include adds relations while retaining the normal scalar payload, so it does not hide sensitive root scalars. omit is a denylist and depends on generator and Prisma version support.</p><p>Do not combine select, include, and omit at one level. They are alternative projection forms.</p><p>Relation counts are another projection node, not a summary automatically coupled to the loaded relation. If a returned to-many relation has an account filter, its _count needs the corresponding filter when clients expect both values to describe the same population. Test the emitted relation condition and count condition separately.</p><p>Defaults inside a nested projection are synthesized structurally. A declared relation object can retain its forced filter and page bound when the client asks for the relation with Boolean shorthand. Client permissions such as an allowed sort field do not invent a sort direction when the client omits one. Tests should therefore cover omitted root projection, explicit nested projection, and relation shorthand rather than assuming one case proves the whole tree.</p><p>Mutation projection is intentionally asymmetric. A mutation shape can validate a client-requested projection. Without enforceProjection, a client that requests no projection causes no shape projection to be emitted, and normal Prisma no-projection behavior applies. Enable projection enforcement when every mutation response must use the declared fields.</p><p>Tests must observe the right phase. guard.query(...).parse() is useful for read filtering and bounds. Read projection defaults appear when the guarded delegate executes. Mutation projection also needs the guarded mutation path.</p><p>The second review question is not “does this query have a select?” Ask which root fields, relation fields, relation rows, and counts can leave through every caller contract.</p><h3>Question three: which write can execute?</h3><p>A generated write endpoint accepts Prisma-shaped arguments. The data shape decides which values the client supplies, which values the server adds, and which nested operations exist.</p><p>Create shapes fail when a required field is unaccounted for. A field may be client-controlled, forced, covered by a Prisma default, covered by a supported Zod default or catch, injected as a scope foreign key, or satisfied through an allowed relation write.</p><pre>const createSubscriptionShape = {<br>  data: {<br>    externalKey: (base) =&gt; base.min(1).max(100),<br>    planId: true,<br>    status: &#39;trialing&#39;,<br>    seatCount: (base) =&gt; base.int().min(1).max(500),<br>    version: 0,<br>  },<br>  select: {<br>    id: true,<br>    externalKey: true,<br>    status: true,<br>    seatCount: true,<br>  },<br>}</pre><p>A generated scope foreign key should not become a client-controlled create field. Trusted request context supplies the scope root, and the extension injects the mapped foreign key on supported top-level writes.</p><p>Bulk mutation safety has two gates. updateMany, returning update-many variants, and deleteMany need a where vocabulary in the shape. The runtime request must also resolve to a meaningful client condition. An empty body, empty operator object, or vacuous logical branch is not a safe bulk filter.</p><p>Guarded batch create methods require an array rather than silently wrapping one object. Provider support still matters for returning batch operations and options such as duplicate skipping.</p><p>Upsert is three contracts, not one data shape:</p><pre>const upsertSubscriptionShape = {<br>  where: {<br>    externalKey: true,<br>  },<br>  create: {<br>    externalKey: true,<br>    planId: true,<br>    status: &#39;trialing&#39;,<br>    seatCount: true,<br>    version: 0,<br>  },<br>  update: {<br>    planId: true,<br>    seatCount: true,<br>  },<br>}</pre><p>The create half must be complete. Update fields remain optional. A forced field in create establishes an insertion value; the same force in update rewrites that value on every existing-record path.</p><p>Unique mutations use direct Prisma unique-selector syntax. Normal filter operator objects belong to non-unique filtering operations, not a top-level unique where shape.</p><p>Relation writes require a separate ownership decision. A shape can permit connect, restrict selector keys, and reject unlisted nested operations. It does not make top-level scope descend into that selector. Application code or database constraints must enforce ownership when the relation target matters.</p><p>Count-only batch methods also have a different return contract from single-record writes. createMany, updateMany, and deleteMany return a batch payload and do not accept a projection. Returning batch variants can support projections when both Prisma and the selected provider support them. If generator configuration redirects a route to a returning method, review its response shape as a changed API rather than an internal optimization.</p><p>The third review question is not “is the method enabled?” Ask which data fields, selector forms, bulk conditions, relation operations, and return fields the method exposes.</p><h3>One contract, several enforcement layers</h3><p>Shapes are strongest when their limits are stated alongside the mechanisms around them.</p><p>Authenticated request state supplies trusted context. Scope mappings inject supported top-level tenant predicates. Caller variants choose one declared shape. Hooks perform bounded application checks that may reject. Purpose-built handlers own queries shapes cannot represent. Database policy handles invariants that must survive every access path.</p><p>No one layer should pretend to cover the others.</p><p>That makes review faster. A pull request adding a generated endpoint can answer three concrete questions:</p><ol><li>Who controls every accepted value?</li><li>Which fields and relations can leave?</li><li>Which mutations and selectors can execute?</li></ol><p>Then tests can target the claim. Parse read arguments for filter mechanics. Execute guarded delegates for projections and writes. Inspect the extension path for scope injection. Use multi-tenant database fixtures when the claim concerns returned rows. Use HTTP tests when the claim concerns transport or generated routing.</p><p>Negative tests carry equal weight. For every audience, attempt one unlisted root field, one sensitive nested scalar, one excessive relation bound, and one forbidden write operation. Positive tests show the intended request works. Negative tests show the declared edge remains closed after model and generator changes.</p><p>A query shape earns the word “contract” when it is explicit about both permission and limitation. That precision lets generation remove repeated code without turning the Prisma argument language into an accidental public API.</p><p>Full syntax, exact errors, version-specific behavior, and reproducible labs are available in the <a href="https://multipliedtwice.github.io/prisma-generator-express/">deeper Field Guide</a>.</p><p>Disclosure: This essay was AI-assisted and verified by the prisma-generator-express maintainer against the project sources and pinned labs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2369e3ff103b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generate Prisma CRUD Routes Without Losing Control]]></title>
            <link>https://ivibe.medium.com/generate-crud-keep-the-api-decisions-13376736b371?source=rss-d2e051ee0d80------2</link>
            <guid isPermaLink="false">https://medium.com/p/13376736b371</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[code-generation]]></category>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[DT]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 21:45:28 GMT</pubDate>
            <atom:updated>2026-08-18T03:51:17.220Z</atom:updated>
            <content:encoded><![CDATA[<p>Let the generator write repeated route code while your application keeps the important decisions.</p><p>CRUD handlers repeat facts already present in a Prisma schema. A model name becomes a route segment. Scalar types become input checks. Prisma operations become controller methods. Relations become another round of request parsing and response shaping.</p><p>Project context: this evaluates a maintainer-built open-source implementation through its current documentation and reproducible labs, not through claimed market adoption.</p><p>The repetition is expensive because it looks harmless. Every copied handler creates another place for pagination defaults, allowed fields, tenant context, and error behavior to drift.</p><p>prisma-generator-express moves that mechanical work into prisma generate. It can emit routers for Express, Fastify, or Hono. prisma-guard adds generated Prisma-aware validation and scope metadata, while operation shapes declare the arguments each caller may use.</p><p>The result is not an application with no code. It is an application with less boundary plumbing and clearer ownership of the remaining decisions.</p><p>That distinction matters. Generation should accelerate work the schema can describe. Authentication, operation exposure, caller trust, and policies that require application or database knowledge still belong to application code.</p><h3>Move the repeatable work into one generation step</h3><p>A generated API begins with three related outputs: Prisma Client, guard metadata, and HTTP routers.</p><pre>generator client {<br>  provider = &quot;prisma-client-js&quot;<br>}</pre><pre>generator guard {<br>  provider          = &quot;prisma-guard&quot;<br>  output            = &quot;../generated/guard&quot;<br>  enforceProjection = &quot;true&quot;<br>}</pre><pre>generator express {<br>  provider = &quot;prisma-generator-express&quot;<br>  target   = &quot;express&quot;<br>}</pre><p>One npx prisma generate command refreshes those artifacts after a schema or generator configuration change.</p><p>The schema remains the data model. Generated router files remain build output. Route configuration decides which operations are mounted. Guard shapes decide which Prisma arguments callers may express.</p><p>That separation is more useful than treating generated code as a replacement for architecture. The cover illustration has two inputs on purpose: schema generation supplies repeatable mechanics, while application policy supplies trust decisions and route exposure.</p><p>If a rule cannot be represented accurately by the generator or guard shape, it should not be squeezed into configuration. A purpose-built handler or database policy is a better boundary than a misleading declarative one.</p><p>Generation also changes the unit of review. Handwritten CRUD invites reviewers to inspect repeated parsing and delegation line by line. Generated CRUD moves that review toward a smaller set of inputs: the Prisma schema, generator options, route descriptors, shapes, and trusted context resolver.</p><p>That does not make generated output irrelevant. It makes direct edits to it the wrong control point. If a route is wrong, change the configuration that produces it and regenerate. A patch inside an emitted router can disappear on the next schema update and leaves no durable explanation of the intended contract.</p><p>Version changes deserve the same treatment. Pin Prisma, the guard, and the router generator together, regenerate in a clean checkout, and run contract tests against the result. Generated code is still a dependency surface even when the repository does not treat each emitted line as authored application code.</p><p>The practical speed gain comes from repeatability. One schema edit can refresh validation metadata, client types, and router mechanics. Review stays focused on the comparatively small policy layer that cannot be inferred from the model.</p><h3>Let one model serve several deliberate contracts</h3><p>A single Prisma model can supports several product surfaces.</p><p>A hotel room may appear in a public search, a partner feed, and a staff console. Those callers should not share one union of every allowed field and operation.</p><p>Named shapes let one generated operation carry separate contracts:</p><pre>const roomRoutes = {<br>  findMany: {<br>    shape: {<br>      storefront: {<br>        where: {<br>          isPublished: { equals: force(true) },<br>          name: { contains: true },<br>        },<br>        select: { id: true, name: true, nightlyRate: true },<br>        take: { max: 40, default: 20 },<br>      },<br>      backoffice: {<br>        where: {<br>          name: { contains: true },<br>          floor: { equals: true },<br>        },<br>        select: {<br>          id: true,<br>          name: true,<br>          nightlyRate: true,<br>          floor: true,<br>          internalNote: true,<br>        },<br>        take: { max: 200, default: 50 },<br>      },<br>    },<br>  },<br>}</pre><p>Each key is a complete API contract. The public caller cannot widen its projection to internalNote because that field is absent from the public shape. Staff can receive a larger projection without forcing every client onto a separate handwritten router.</p><p>Use shape when only the Prisma contract changes. Use variants when a matched caller also needs its own hooks.</p><p>The choice of caller is part of the boundary. A request header is client input. It is appropriate for intentionally public contracts, such as compact and detailed public views. It should not select a privileged staff contract.</p><p>For privileged contracts, use resolveVariant with authenticated server state. Exact caller keys match before parameterized keys. A default key accepts missing, blank, and unmatched callers, so it should exist only when all three cases may receive that fallback.</p><p>An omitted contract can be more valuable than another authorization branch. If partners must never delete rooms, leave the partner key out of the generated delete operation.</p><p>Review caller routing as a matrix: operations on one axis, audiences on the other. A cell should contain a shape and any justified hooks, or remain deliberately empty.</p><p>Keep those contracts independently named even when they share several fields. Reuse is safe within one exposure class, but a shared object across public and privileged audiences can make a future field addition widen both endpoints. A little duplication at a trust boundary can reduce the cognitive load of proving who receives what.</p><p>Parameterized caller keys add another reason to use the built-in resolver instead of recreating selection in a hook. The router distinguishes the raw caller from the declared key that matched it and rejects ambiguous parameter patterns. A handwritten string branch has to reproduce exact matching, parameter precedence, defaults, and failure behavior before it can claim the same contract.</p><h3>Use hooks for lifecycle decisions, not hidden query construction</h3><p>Generated routes do not remove application decisions. They provide defined places for them.</p><p>For a successfully routed variant, the lifecycle is operation before-hooks, variant before-hooks, generated handler, variant after-hooks, then operation after-hooks.</p><p>Operation hooks fit policy shared by every caller on that operation. Variant hooks fit work specific to one declared caller contract.</p><pre>const transferRoutes = {<br>  update: {<br>    before: [authenticateOperator],<br>    variants: {<br>      warehouse: {<br>        before: [authorizeTransferLocation],<br>        shape: warehouseTransferShape,<br>      },<br>      supervisor: {<br>        before: [requireSupervisorApproval],<br>        shape: supervisorTransferShape,<br>      },<br>    },<br>  },<br>}</pre><p>A before-hook can inspect the exact identifier the generated handler will use and reject the request. It should not authorize one id and silently rewrite another.</p><p>Stable Prisma restrictions belong in shapes. Top-level tenant filters belong in generated scope mappings and trusted context. Caller differences belong in variants.</p><p>When the server must author an entire query that shapes cannot represent, use a purpose-built handler. That is especially important for a genuine server-owned disjunction. Forced conditions inside Boolean combinators become mandatory constraints; they are not a general way to express arbitrary authorization logic.</p><p>After-hooks are optional post-handler work, not cleanup. A terminal response or error can prevent later phases from running. Resources that must always be released need a lifecycle with explicit finally behavior outside generated after-hooks.</p><p>Target details also remain real. Express, Fastify, and Hono use different hook signatures and short-circuit mechanics. The placement principle stays consistent, but application code must follow the selected target’s contract.</p><h3>Keep trusted context outside Prisma arguments</h3><p>Tenant identity and authenticated caller state should not travel as client-controlled query fields.</p><p>Mark a tenant model with @scope-root, generate the scope map, and extend Prisma Client with a context resolver:</p><pre>const prisma = new PrismaClient().$extends(<br>  guard.extension(() =&gt; ({<br>    Nursery: requestStore.getStore()?.nurseryId,<br>  }))<br>)</pre><p>The value comes from authenticated request-local state. The extension injects it into supported top-level operations on mapped child models.</p><p>This is a concrete feature, not a promise that every relation is automatically protected. Scope does not descend into nested reads or writes. Root delegates are not filtered by their own root marker. Models without generated mappings need another explicit boundary.</p><p>Generated speed remains useful because those limitations are visible. The scope map can be reviewed. Nested projections can carry their own filters and bounds. Exceptional ownership rules can move to application code or the database.</p><p>Custom application state should remain in request context. Adding caller or authorization metadata to a Prisma body makes the data contract harder to reason about and can fail strict guard validation.</p><h3>Treat route exposure as product design</h3><p>A generator can emit handlers for many Prisma operations. That does not mean every handler should be mounted.</p><p>Review reads, unique mutations, bulk mutations, relation writes, and returning methods separately. Provider support differs for some returning bulk operations. A route with neither shape nor variants calls Prisma without guard enforcement.</p><p>A focused setup is not enableAll followed by scattered denial checks. Start with a small explicit surface and grow it when a product workflow needs another operation.</p><p>Read projection deserves the same attention. On guarded reads, a shape-level select or include acts as whitelist and default when the client omits projection. Mutation projection has different defaults and needs enforceProjection when omission must never widen the response.</p><p>Bulk routes require a separate decision. A bulk method may be valid in the generated surface only when its shape declares a filtering vocabulary, and the runtime request still needs a meaningful client condition. Enabling deleteMany because single-record delete is allowed skips that second risk review. Returning bulk variants also depend on provider and Prisma support, so route configuration should describe the method the deployed database can execute, not the method a product plan merely prefers.</p><p>OpenAPI output can describe route paths and shape-derived request structure. It cannot infer application policy hidden inside arbitrary hook functions. If a hook rejects transfers outside an operator’s warehouse, document that condition beside the route configuration and test it as application behavior. Generated documentation should not be treated as proof of logic it cannot inspect.</p><p>GET and POST read twins should share one query contract. GET uses encoded query parameters; POST accepts native JSON for larger argument trees. A hook that mutates only the body creates transport-dependent semantics, so stable restrictions should not live there.</p><h3>Adopt generation without surrendering review</h3><p>A practical evaluation sequence is small:</p><ol><li>Generate one read-only model router.</li><li>Expose only required operations.</li><li>Add one direct shape with an explicit projection and page bound.</li><li>Verify the emitted Prisma arguments.</li><li>Add trusted scope context if the model is tenant-mapped.</li><li>Split one operation into caller contracts only when audiences differ.</li><li>Add hooks only for decisions shapes, scope, and variants cannot own.</li><li>Add writes after create completeness, bulk filtering, and relation ownership have explicit tests.</li></ol><p>Keep real-guard contract tests even when browser E2E uses a configuration that drops guard validation. Browser tests can cover routing and UI behavior; they cannot prove a production shape rejects a field when the guard is absent.</p><p>Generation pays off when it narrows the application’s work to meaningful decisions. Prisma describes data. Generators emit repeatable mechanics. Shapes define allowed calls. Application code supplies trust, product policy, and the exceptions that cannot be declared honestly.</p><p>The exhaustive behavior, compatibility notes, and reproducible evidence remain in the <a href="https://multipliedtwice.github.io/prisma-generator-express/">deeper Field Guide</a>.</p><p>Disclosure: This essay was AI-assisted and verified by the prisma-generator-express maintainer against the project sources and pinned labs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13376736b371" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Make Prisma v7 Faster 5x Without Rewriting a Single Query]]></title>
            <link>https://ivibe.medium.com/how-i-made-our-prisma-api-5x-faster-without-rewriting-a-single-query-4a113edd1f46?source=rss-d2e051ee0d80------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a113edd1f46</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[orm]]></category>
            <dc:creator><![CDATA[DT]]></dc:creator>
            <pubDate>Thu, 22 Jan 2026 10:20:16 GMT</pubDate>
            <atom:updated>2026-01-31T17:47:32.634Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qn894U1DuA1EJYqNM-qIgg.png" /></figure><p><em>A developer’s journey from “Prisma is amazing” to “wait, why is this so slow?” to building a solution that keeps both the DX and performance.</em></p><h3>The Problem I Didn’t See Coming</h3><p>Few months ago, our API was humming along nicely. We’d chosen Prisma for our database layer, and honestly, it felt like magic. Type-safe queries? Check. Auto-generated types? Check. Migrations that actually work? Double check.</p><p>Then traffic started ramping up.</p><p>Our /dashboard endpoint started timing out. Our analytics queries were crawling. Response times were creeping into multiple seconds.</p><p><strong>The culprit? Every database read operation was taking 2–3x longer than it should.</strong></p><h3>The Developer’s Dilemma</h3><p>Here’s the thing about Prisma that nobody tells you upfront: it’s an <strong>architectural tradeoff</strong>, not a magic bullet.</p><p>When you write this:</p><pre>const users = await prisma.user.findMany({<br>  where: { status: &#39;ACTIVE&#39; },<br>  include: { posts: true }<br>})</pre><p>What happens is:</p><ol><li>Your TypeScript query gets validated against your schema</li><li>It’s converted to Prisma’s internal query format</li><li>The query engine (TypeScript in v7, previously Rust) processes it</li><li>SQL gets generated and executed</li><li>Results flow back through the engine</li><li>Finally serialized to typed JavaScript objects</li></ol><p><strong>That’s a lotta layers.</strong></p><p>Even with v7’s TypeScript engine, each step adds overhead. The engine provides safety and correctness, but every validation and transformation takes time. On simple queries, you might not notice. But when you’re running complex analytics across 100k rows, or serving 1000 requests/minute, those milliseconds compound into real problems.</p><h3>The Paths I Considered (And Rejected)</h3><p>When I brought this up with the team, the suggestions were predictable:</p><p><strong>Option 1: “Just use raw SQL for the slow queries”</strong></p><p>Sure, but then I lose type safety. And I have to maintain two different query systems. And new team members have to learn both. Hard pass.</p><p><strong>Option 2: “Switch to Drizzle/Kysely/[insert ORM here]”</strong></p><p>Great ORMs, but that’s a multi-month migration. We’d have to rewrite hundreds of queries, update all our types, retrain the team, and pray we don’t introduce bugs. Nobody had the bandwidth for that.</p><p><strong>Option 3: “Add aggressive caching”</strong></p><p>We tried. Redis helped, but cache invalidation became its own nightmare. Plus, it doesn’t solve the fundamental issue — our queries are still slow when cache misses happen.</p><h3>An Earthquake and an Idea</h3><p>On March 28, 2025, a massive 7.7 magnitude earthquake struck Myanmar near Mandalay, killing over 3,000 people and causing widespread devastation. The tremors traveled over 1,000 kilometers to Bangkok, where the city’s soft soil amplified the seismic waves. Buildings swayed, a 33-story construction site collapsed killing 95 people, and the city went into emergency mode.</p><p>I grabbed my laptop and headed out of the city to Bang Kachao — a green area across the river where I could think clearly without aftershock alerts.</p><p>I’d been a bit <a href="https://multipliedtwice.github.io/prisma-to-sql/">upset with the Prisma performance</a> for weeks. Sitting under a tree with spotty internet, I started sketching out an idea: <strong>What if we could pre-generate SQL at build time?</strong></p><p>The concept was simple: during prisma generate, analyze the schema and create optimized SQL queries for common operations. Store them in a generated folder. At runtime, just execute the pre-baked SQL directly.</p><p>I started coding. No distractions, no meetings, just me and the problem.</p><p><strong>What I didn’t know then was how long this would actually take.</strong> Building a correct SQL compiler for a package with 44.8k GitHub stars — one that developers trust with their production databases — turned out to be far more complex than I initially thought. It would take almost a year of development, countless edge cases, and comprehensive testing before I’d be confident enough to release it.</p><h3>The First (Failed) Attempt</h3><p>My initial idea was to intercept Prisma’s debug queries.</p><p>Prisma has a log option that outputs the SQL it generates:</p><pre>const prisma = new PrismaClient({<br>  log: [{ emit: &#39;event&#39;, level: &#39;query&#39; }]<br>})</pre><pre>prisma.$on(&#39;query&#39;, (e) =&gt; {<br>  console.log(&#39;Query: &#39; + e.query)<br>  console.log(&#39;Params: &#39; + e.params)<br>})</pre><p>I thought: “If I can capture these SQL strings, I can execute them directly via postgres.js and skip the engine entirely.”</p><p><strong>It didn’t work.</strong></p><p>The approach had fundamental issues with how parameters were handled and the rigidity of trying to work with pre-generated SQL strings. It became clear this wasn’t the right path.</p><p>Back to the drawing board.</p><h3>The Breakthrough</h3><p>After months of work, I had a working prototype that generated SQL at build time. But when I benchmarked it, something unexpected happened: <strong>even the runtime SQL generation (without pre-baking) was dramatically faster than going through Prisma’s engine.</strong></p><p>The pre-baking was a nice optimization, but it turned out the real bottleneck wasn’t the SQL generation — it was all those engine layers. By generating SQL directly from Prisma’s query format and executing it via postgres.js, I was bypassing the entire overhead.</p><p>The key insight? Prisma exposes its complete schema metadata through DMMF (Data Model Meta Format). With that information, I could convert Prisma queries directly to SQL without needing the engine at all.</p><h3>Building the Solution</h3><p>I spent the next few months refining the approach:</p><ol><li><strong>A query builder</strong> that converts Prisma’s query format directly into optimized SQL</li><li><strong>Direct execution</strong> via postgres.js (and later better-sqlite3)</li><li><strong>A Prisma extension</strong> that intercepts read operations seamlessly</li><li><strong>Support for both modes</strong>: runtime SQL generation (fast) and pre-baked queries (even faster)</li></ol><p>The goal was pragmatic: <strong>keep Prisma for everything it’s great at (migrations, schema management, type generation, writes), but execute read queries directly through a native database driver.</strong></p><p>I wrote tests. Lots of tests. 137 E2E test cases covering every query pattern I could think of, validated against both Prisma v6, v7 and Drizzle to ensure it all makes sense.</p><h3>The One-Line Integration</h3><p>As simple as that:</p><pre>import { speedExtension } from &#39;prisma-sql&#39;<br>import postgres from &#39;postgres&#39;<br>import { Prisma } from &#39;@prisma/client&#39;<br><br>const sql = postgres(process.env.DATABASE_URL)<br>const prisma = new PrismaClient().$extends(<br>  speedExtension({ postgres: sql })<br>)</pre><p>That’s it. <strong>Seven lines of setup code.</strong> No query rewrites. No migration. No breaking changes.</p><h3>The Results Were Surprising</h3><p>Here’s what happened:</p><p><strong>Complex aggregation queries:</strong></p><ul><li>Before: ~800ms average</li><li>After: ~150ms average</li><li><strong>Speedup: 5–7x</strong></li></ul><p><strong>Queries with nested relations:</strong></p><ul><li>Before: ~230ms average</li><li>After: ~90ms average</li><li><strong>Speedup: 2.5x</strong></li></ul><p><strong>Simple lookups:</strong></p><ul><li>Before: ~45ms average</li><li>After: ~18ms average</li><li><strong>Speedup: 2.5x</strong></li></ul><p><strong>Count queries for pagination:</strong></p><ul><li>Before: ~150ms average</li><li>After: ~22ms average</li><li><strong>Speedup: 6–7x</strong></li></ul><p>Our overall P95 response time dropped from over a second to under 400ms. The difference was immediately visible in our monitoring dashboard.</p><p>These numbers are typical for PostgreSQL. SQLite queries showed even more dramatic improvements — averaging 5.5x faster, with some operations hitting 7x.</p><h3>How It Works Under the Hood</h3><p>The extension intercepts Prisma’s read operations (findMany, findFirst, findUnique, count, aggregate, groupBy), generates optimized SQL directly from your query, and executes it via postgres.js or better-sqlite3.</p><p><strong>For reads:</strong> TypeScript → SQL → Database (fast path, bypasses the engine)</p><p><strong>For writes:</strong> TypeScript → Prisma Engine → Database (safe path, unchanged)</p><p>You get raw SQL performance for reads while keeping Prisma’s safety features for writes where they matter most.</p><p>The pre-baking feature (the original idea) is optional — you can add a generator to your schema that creates build-time SQL for your most common queries using @optimize directives, reducing overhead even further. But most people don&#39;t need it; runtime generation is already fast enough.</p><h3>Limitations:</h3><ol><li><strong>It’s read-only optimization.</strong> Writes (create, update, delete) still go through Prisma&#39;s engine. That&#39;s actually fine—writes are less frequent and the overhead matters less.</li><li><strong>Not every Prisma feature is supported.</strong> Some advanced query features fall back to standard Prisma. The extension is smart about this — if it can’t optimize a query, it just uses regular Prisma.</li><li><strong>PostgreSQL and SQLite only.</strong> MySQL support is on the roadmap but not there yet. If you’re on MySQL, ping me on Github.</li><li><strong>It’s another dependency.</strong> But it’s MIT licensed, has comprehensive tests, and I’m actively maintaining it.</li></ol><h3>The Developer Experience Was Unchanged</h3><p>After deployment, I reviewed our codebase:</p><ul><li>✅ All existing queries work identically</li><li>✅ TypeScript types are exactly the same</li><li>✅ Error handling unchanged</li><li>✅ Team members didn’t need to learn anything new</li><li>✅ Prisma Studio still works</li><li>✅ Migrations still work</li><li>✅ All our tests passed without modification</li></ul><p><strong>Zero breaking changes.</strong> It was suspiciously smooth.</p><h3>The Unexpected Benefits</h3><p>Beyond raw speed, we got some surprising wins:</p><p><strong>1. Simpler Architecture</strong> We removed Redis caching for several endpoints because queries were fast enough without it. Less infrastructure = less complexity.</p><p><strong>2. Better Resource Utilization</strong> Faster queries = less database load. We’re getting better performance with the same infrastructure.</p><p><strong>3. Debug Visibility</strong> The extension has an onQuery callback that helped us identify our actual slow queries (turns out most of our &quot;slow&quot; queries were just fighting with the engine overhead).</p><pre>speedExtension({<br>  postgres: sql,<br>  models,<br>  onQuery: (info) =&gt; {<br>    console.log(`${info.model}.${info.method}: ${info.duration}ms`)<br>  }<br>})</pre><h3>Should You Try This?</h3><p>Here’s my honest take on when this makes sense:</p><h3>✅ Good fit if you:</h3><ul><li>Have read-heavy workloads (most APIs are)</li><li>Are hitting Prisma performance issues at scale</li><li>Want to keep Prisma’s DX but need better performance</li><li>Use PostgreSQL or SQLite</li><li>Want to reduce infrastructure load</li></ul><h3>❌ Not for you if:</h3><ul><li>Write-heavy workloads (it doesn’t optimize writes)</li><li>Using MySQL (not supported yet)</li><li>Haven’t actually measured that Prisma is your bottleneck</li><li>Need bleeding-edge Prisma features that aren’t supported yet</li></ul><h3>The Bigger Picture</h3><p>This experience taught me something important about architectural decisions: <strong>the best tool is the one that grows with you.</strong></p><p>Prisma was the right choice when we started. The type safety and DX let us move fast and ship features confidently. But as we scaled, we hit its limitations.</p><p>Rather than throwing away months of work to migrate to a “faster” ORM, I found a way to enhance what we already had. That’s the kind of pragmatic engineering I wish I’d learned earlier in my career.</p><h3>Try It Yourself</h3><p>If you’re dealing with similar Prisma performance issues, here’s how to test it in your codebase:</p><ol><li><strong>Benchmark your current queries</strong> (you need a baseline)</li></ol><ul><li>console.time(&#39;query&#39;) await prisma.user.findMany({ where: { ... } }) console.timeEnd(&#39;query&#39;)</li></ul><ol><li><strong>Install the extension</strong></li><li>npm install prisma-sql postgres</li><li><strong>Add it to one service</strong> (don’t go all-in immediately)</li><li><strong>Compare results</strong> (measure, don’t guess)</li><li><strong>Roll out gradually</strong> (test in staging, then production)</li></ol><p>The full documentation is on <a href="https://github.com/multipliedtwice/prisma-to-sql">GitHub</a> and <a href="https://www.npmjs.com/package/prisma-sql">NPM</a>.</p><h3>What’s Next</h3><p>I’m actively working on:</p><ul><li>Write operation support (the logical next step after optimizing reads)</li><li>MySQL support</li><li>More advanced aggregation support</li></ul><p>If you try it out, I’d love to hear your feedback. Open an issue on GitHub or reach out directly.</p><h3>Final Thoughts</h3><p>Would I recommend this to every Prisma user? No. If your queries are fast enough, don’t optimize them.</p><p>Would I recommend it to teams hitting performance walls? Yep. It bought us months of runway without a costly migration.</p><p>The best part? <strong>We’re still using Prisma.</strong> We didn’t have to give up the tool we love — we just made it work better for our specific use case.</p><p><em>If you have questions about the implementation or want to contribute, the repo is open and I’m happy to discuss the technical details.</em></p><p><strong>Links:</strong></p><ul><li>📦 <a href="https://www.npmjs.com/package/prisma-sql">NPM Package</a></li><li>🔧 <a href="https://github.com/multipliedtwice/prisma-to-sql">GitHub Repository</a></li><li>📊 <a href="https://multipliedtwice.github.io/prisma-to-sql/">Full Benchmarks &amp; Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a113edd1f46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Generate a Type-Safe, Secure Node.js]]></title>
            <link>https://ivibe.medium.com/how-to-build-a-type-safe-secure-node-js-api-with-prisma-typegraphql-and-graphql-query-purifier-18727f73d084?source=rss-d2e051ee0d80------2</link>
            <guid isPermaLink="false">https://medium.com/p/18727f73d084</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[typegraphql]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[DT]]></dc:creator>
            <pubDate>Sat, 18 Nov 2023 18:33:33 GMT</pubDate>
            <atom:updated>2023-11-20T03:12:21.040Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Generate a Type-Safe, Secure Node.js API with Prisma, TypeGraphQL, and graphql-query-purifier</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wllGmY5URJbMdrnKc_WFUQ.png" /></figure><p>Building a Node.js API efficiently while ensuring data security and type safety can be challenging. This guide demonstrates a streamlined process using <a href="https://prisma.typegraphql.com/">Prisma, TypeGraphQL</a>, and <a href="https://github.com/multipliedtwice/graphql-query-purifier">graphql-query-purifier</a>.</p><blockquote>The full example is available in <a href="https://github.com/multipliedtwice/graphql-query-purifier-example">repository</a></blockquote><h3>Setting Up the Node.js Project and Prisma Integration</h3><p>Start by initializing a Node.js project and integrating Prisma for database management:</p><pre>mkdir nodejs-api &amp;&amp; cd nodejs-api<br>npm init -y<br>npm i --save-dev @types/cors@2.8.16 @types/graphql-fields@1.3.9 @types/node@20.9.2 body-parser@1.20.2 cors@2.8.5 express@4.18.2 graphql-query-purifier prisma@5.6.0 ts-node@10.9.1 type-graphql@2.0.0-beta.1 typegraphql-prisma@0.27.1 typescript@5.2.2<br>npm i @apollo/server@4.9.5 @prisma/client@5.6.0 graphql@16.8.1 graphql-fields@2.0.3 graphql-scalars@1.22.4 reflect-metadata@0.1.13<br>npx tsc --init<br>npx prisma init --datasource-provider sqlite</pre><h3>Defining Prisma Models</h3><p>Create a Prisma schema to represent a company structure:</p><pre>// schema.prisma<br>datasource db {<br>  provider = &quot;sqlite&quot;<br>  url      = &quot;file:./dev.db&quot;<br>}<br><br>generator client {<br>  provider = &quot;prisma-client-js&quot;<br>}<br><br>generator typegraphql {<br>  provider = &quot;typegraphql-prisma&quot;<br>  output   = &quot;generated&quot;<br>}<br><br>model Employee {<br>  id           Int        @id @default(autoincrement())<br>  name         String<br>  departmentId Int<br>  department   Department @relation(fields: [departmentId], references: [id])<br>  salary       Salary?<br>  salaryId     Int?<br>}<br><br>model Department {<br>  id        Int        @id @default(autoincrement())<br>  name      String<br>  employees Employee[]<br>}<br><br>model Salary {<br>  id         Int      @id @default(autoincrement())<br>  amount     Float<br>  employeeId Int      @unique<br>  employee   Employee @relation(fields: [employeeId], references: [id])<br>}</pre><p>Run migrations:</p><pre>npx prisma migrate dev --name init</pre><h3>Setting Up Apollo Server with Express</h3><p>Integrate Apollo Server with Express:</p><pre>import &quot;reflect-metadata&quot;;<br>import express from &quot;express&quot;;<br>import { ApolloServer } from &quot;@apollo/server&quot;;<br>import { GraphQLQueryPurifier } from &quot;graphql-query-purifier&quot;;<br>import { resolvers } from &quot;../prisma/generated&quot;;<br>import { PrismaClient } from &quot;@prisma/client&quot;;<br><br>import cors from &quot;cors&quot;;<br>import path from &quot;path&quot;;<br>import { json, urlencoded } from &quot;body-parser&quot;;<br>import { expressMiddleware } from &quot;@apollo/server/express4&quot;;<br>import { buildSchema } from &quot;type-graphql&quot;;<br><br>const startServer = async () =&gt; {<br>  const app = express();<br>  const prisma = new PrismaClient();<br><br>  app.use(cors(), json(), urlencoded({ extended: true }));<br><br>  const gqlPath = path.resolve(__dirname, &quot;../frontend&quot;);<br>  const queryPurifier = new GraphQLQueryPurifier({<br>    gqlPath,<br>    allowStudio: true,<br>    // allowAll: false,<br>  });<br>  app.use(queryPurifier.filter);<br><br>  const server = new ApolloServer({<br>    schema: await buildSchema({<br>      resolvers,<br>      validate: false,<br>    }),<br>  });<br><br>  await server.start();<br><br>  const context = expressMiddleware(server, {<br>    context: async (_ctx) =&gt; ({<br>      prisma,<br>    }),<br>  });<br><br>  app.use(&quot;/graphql&quot;, context);<br><br>  const PORT = process.env.PORT || 3000;<br>  app.listen(PORT, () =&gt; {<br>    console.log(`Server running on http://localhost:${PORT}/graphql`);<br>  });<br>};<br><br>startServer();</pre><h3>Testing the API</h3><p>Validate API functionality with GraphQL queries:</p><h4>Valid Query:</h4><pre># Fetch departments and their employees<br>query {<br>  departments {<br>    id<br>    name<br>    employees {<br>      id<br>      name<br>    }<br>  }<br>}</pre><h4>Malicious Query Attempt:</h4><pre># Unauthorized attempt to access salaries<br>query {<br>  departments {<br>    id<br>    name<br>    employees {<br>      id<br>      name<br>      salary {<br>        amount<br>      }<br>    }<br>  }<br>}</pre><figure><img alt="typegraphql-prisma query filtering" src="https://cdn-images-1.medium.com/max/1024/1*6UMf-I_tgF_tFfYs0k4zbQ.png" /></figure><h3>Conclusion</h3><p>This guide presented a method to create a Node.js API using TypeGraphQL, graphql-query-purifier, and architectural considerations. Key points include:</p><ul><li>TypeGraphQL for Schema and Resolvers: Auto-generation from Prisma models accelerates API creation with CRUD capabilities. Strong typing with TypeScript enhances API quality.</li><li>Security with graphql-query-purifier: Filters queries to protect sensitive data, preventing unauthorized access and over-fetching.</li><li>Practical Outcomes: Combining these tools yields a secure, scalable API. It reduces development time and positions the API for future challenges.</li></ul><p>This method offers a streamlined approach to developing modern web applications, ensuring rapid development, security, and type safety.</p><p>At the end we got a set of resolvers that is enough for most of daily operations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Azlvudb4TF5vTCJlfDn7kg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18727f73d084" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Backticks-codeblocks and string parsing]]></title>
            <link>https://ivibe.medium.com/exploring-backticks-codeblocks-a-simple-tool-for-markdown-code-parsing-00934002677b?source=rss-d2e051ee0d80------2</link>
            <guid isPermaLink="false">https://medium.com/p/00934002677b</guid>
            <category><![CDATA[code-block]]></category>
            <category><![CDATA[backtick]]></category>
            <category><![CDATA[markdown]]></category>
            <dc:creator><![CDATA[DT]]></dc:creator>
            <pubDate>Mon, 06 Nov 2023 03:04:44 GMT</pubDate>
            <atom:updated>2023-11-06T03:15:34.982Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O3Xne8NqGO7JU0o7Ue0tyA.png" /></figure><h3>The Challenge with Markdown Code Segments</h3><p>As someone who frequently dabbles with Markdown, I’ve often grappled with the intricacies of managing code segments. Whether inline code marked by single backticks or larger blocks enclosed within triple backticks, parsing these accurately can be a bit of a headache, especially when you’re knee-deep in Markdown conversion or similar tasks.</p><h3>My Experiment: backticks-codeblocks</h3><p>So, I decided to play around with an idea and ended up creating <a href="https://github.com/multipliedtwice/backticks-codeblocks">backticks-codeblocks</a>. It&#39;s a basic JavaScript tool that helps break down Markdown text into segments of regular text and code. It’s nothing fancy, but it does the job of distinguishing between different types of code segments.</p><h3>What It Does</h3><ol><li>Simple Parsing: It can tell apart inline code from block code.</li><li>Handles Odd Cases: Works around nested or escaped backticks and empty code blocks.</li><li>Light and Fast: I aimed for something that wouldn’t add much weight to your project.</li></ol><h3>Why Did I Make backticks-codeblocks?</h3><p>Honestly, it started as a curiosity project. Markdown engines can be heavy, and sometimes, you need something lightweight to handle code segments. For basic syntax highlighting, formatting text, or converting Markdown to HTML, a simpler tool might be useful for small projects or learning platforms.</p><h3>Can You Help Improve It?</h3><p>Absolutely! backticks-codeblocks is very much a work-in-progress, and I’m all for collaboration. If you’re interested in tinkering with it, feel free to jump in.</p><h3>Ways to Contribute</h3><ol><li>Check Out the Code: It’s all on GitHub [GitHub Repository Link].</li><li>Report Bugs or Ideas: If something doesn’t work or could work better, let me know.</li><li>Fork and Tweak: If you’re into coding, I’d love to see your pull requests.</li><li>Join the Discussion: Share your thoughts or ask questions.</li></ol><h3>What’s There to Do?</h3><ul><li>Testing: More tests are always good.</li><li>Documentation: If you can clarify or add examples, that would be great.</li><li>New Features: Have an idea? I’d love to hear it.</li><li>Optimization: Help it run smoother and faster.</li></ul><h3>Trying It Out</h3><p>Getting started is pretty straightforward:</p><pre>npm install backticks-codeblocks</pre><p>Here’s a quick example:</p><pre>import { processText } from &#39;backticks-codeblocks&#39;;<br><br>const markdown = &#39;Some `inline code` and a block:\n```\nconsole.log(&quot;Hello, world!&quot;);\n```&#39;;<br><br>const segments = processText(markdown);<br>console.log(segments);<br>// Output:<br>// [<br>//   &quot;Some &quot;,<br>//   { code: &quot;inline code&quot;, isBlock: false },<br>//   &quot; and a block:\n&quot;,<br>//   { code: &#39;console.log(&quot;Hello, world!&quot;);&#39;, isBlock: true }<br>// ]</pre><h3>Wrapping Up</h3><p>backticks-codeblocks isn’t going to revolutionize Markdown processing, but it’s my little contribution to making handling code segments a tad easier. If you find it helpful or have suggestions, I’m all ears!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00934002677b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple custom form validation on blur event with Svelte]]></title>
            <link>https://ivibe.medium.com/simple-form-validation-on-blur-event-with-svelte-da731cb63efb?source=rss-d2e051ee0d80------2</link>
            <guid isPermaLink="false">https://medium.com/p/da731cb63efb</guid>
            <category><![CDATA[sapper]]></category>
            <category><![CDATA[regex]]></category>
            <category><![CDATA[form-validation]]></category>
            <category><![CDATA[reactive-form-validation]]></category>
            <category><![CDATA[svelte]]></category>
            <dc:creator><![CDATA[DT]]></dc:creator>
            <pubDate>Tue, 29 Jun 2021 03:41:42 GMT</pubDate>
            <atom:updated>2021-07-06T13:44:16.511Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gFvBXmpkj9V09wO5" /><figcaption>Photo by <a href="https://unsplash.com/@ikukevk?utm_source=medium&amp;utm_medium=referral">Kevin Ku</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Easy way to add <strong>client-side custom form validation </strong>using Svelte and blur event. It helps to makes sure that submitted data matches the requirements for a particular backend endpoint. Normally you would use something like <a href="https://www.npmjs.com/package/svelte-forms">svelte-forms</a>, <a href="https://github.com/tjinauyeung/svelte-forms-lib">svelte-forms-lib</a>, etc.</p><p>For projects of any size, you might want to avoid adding more dependencies for various reasons. So there’s a relatively easy way to validate your forms without any additional library.</p><p>The basis of the approach is the array of tuples that we can pass to input children:</p><pre>const urlRegex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&amp;//=]*)/</pre><pre>const minLengthRegex = /\b\w{3,}\b/</pre><pre>const validationArray = [<br>  [urlRegex, &quot;Invalid url&quot;], <br>  [minLengthRegex, &quot;At least 3 characters&quot;]<br>]</pre><p>Looks somehow similar to Angular Forms, isn’t it? Then we pass this array to children and pick preferable event for handling the validation, I’ve picked on:blur:</p><pre>&lt;input<br>    on:blur={() =&gt; {<br>      invalidRegexes = regex<br>        .filter((r, i) =&gt; {<br>          if (!value.match(r[0])) return true;<br>        })<br>        .filter((v) =&gt; v);<br>    }}<br>    bind:value /&gt;</pre><p>So this snippet will check the value against our validation rules and we will have an array of validation errors.</p><p>Then all we need to do is to render error message all at once or one by one. I decided to do it one by one:</p><pre>{#if invalidRegexes?.length}&lt;span&gt; {invalidRegexes[0][1]} &lt;/span&gt;{/if}</pre><p>Working REPL example is available here: <a href="https://svelte.dev/repl/b7658b2ce7cf4e54a3457fb4b4258631?version=3.38.3">https://svelte.dev/repl/b7658b2ce7cf4e54a3457fb4b4258631?version=3.38.3</a></p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da731cb63efb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Svelte Sapper slow rebuilds?]]></title>
            <link>https://ivibe.medium.com/svelte-sapper-slow-rebuilds-a7c3e27a1a3b?source=rss-d2e051ee0d80------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7c3e27a1a3b</guid>
            <category><![CDATA[rollup]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[svelte]]></category>
            <category><![CDATA[sapper]]></category>
            <category><![CDATA[svelte-3]]></category>
            <dc:creator><![CDATA[DT]]></dc:creator>
            <pubDate>Tue, 20 Apr 2021 03:04:14 GMT</pubDate>
            <atom:updated>2021-09-18T18:24:06.411Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<h3>How to speed up Sapper slow rebuilds and solve VS Code freeze problem?</h3><figure><img alt="Speed up Sapper / Svelte rebuilds" src="https://cdn-images-1.medium.com/max/1024/0*0ns-yPG6NENOWcGJ" /><figcaption>Photo by <a href="https://unsplash.com/@chrisliverani?utm_source=medium&amp;utm_medium=referral">Chris Liverani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I’ve been playing for a while with Sapper and one thing has been making the development experience a little uncomfortable — progressively slower rebuilds and frozen VS Code. Sometimes it becomes so slow, that even autocomplete takes few minutes to appear. It happens because after every file save - rollup creates dozens of copies of the same files with different hash in the name.</p><p>When the project is created — normally `rollup.config.js` uses this setting output: <strong>config.client.output()</strong>. Similar is for the server if you use Sapper.</p><p>This function returns an object like this:</p><pre>{<br>  dir,<br>  entryFileNames: &#39;[name].<strong>[hash]</strong>.js&#39;,<br>  chunkFileNames: &#39;[name].<strong>[hash]</strong>.js&#39;,<br>  format: &#39;esm&#39;,<br>  sourcemap<br>}</pre><p>As it is a dev issue and it doesn’t affect production build — you can try to remove .[hash] and sourcemapright into this file (if you need a quick fix for this problem and your deployment process has proper setup).</p><p>Won’t hurt to add to server output similar settings:</p><pre>entryFileNames: &#39;[name].js&#39;,<br>chunkFileNames: &#39;[name].js&#39;,</pre><p>Of course, it’s hacky, turns off auto-reloads, and breaks error messages. But on relatively large codebases with 300K+ lines, this is probably the only way to keep working.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7c3e27a1a3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>