Skip to content

Validate a Batch Before Committing It

The Course
•
18 min study

The decision

A bulk update should either apply every valid operation or leave the original state intact. Partial success is a different API and must be named explicitly.

Read, predict, run

The model copies the current values, applies operations to the draft and returns the draft only when every operation is valid. It returns the original values on failure. The local persistence exercise later uses a database transaction for the same guarantee:

JavaScript
export function run({ values, changes }) {
  const draft = [...values];
  for (const change of changes) {
    if (
      !Number.isInteger(change.index) ||
      change.index < 0 ||
      change.index >= draft.length
    )
      return { ok: false, values };
    draft[change.index] = change.value;
  }
  return { ok: true, values: draft };
}

Before pressing Run, predict what run returns for {"values": [1, 2], "changes": [{"index": 0, "value": 8}, {"index": 9, "value": 3}]}, from the code above. Write your answers down first: after Run, the case table shows the expected values beside the actual ones.

Validate a Batch Before Committing It Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>Validate a Batch Before Committing It</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run({ values, changes }) { const draft = [...values]; for (const change of changes) { if ( !Number.isInteger(change.index) || change.index < 0 || change.index >= draft.length ) return { ok: false, values }; draft[change.index] = change.value; } return { ok: true, values: draft }; } export const examples = [ [ { values: [1, 2], changes: [ { index: 0, value: 8 }, { index: 9, value: 3 }, ], }, { ok: false, values: [1, 2] }, ], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Check your prediction
  • Input {"values": [1, 2], "changes": [{"index": 0, "value": 8}, {"index": 9, "value": 3}]} → {"ok": false, "values": [1, 2]}.

The case table computes these results on the server side of the simulation. It compares values; it does not prove a production deployment or database works.

The failure to avoid

Writing directly into live state before validating the last operation leaves half a batch committed. A JavaScript copy is useful for a model but does not make multiple database writes atomic.

Compare writing straight into the input (values[change.index] = change.value) with the draft. Trace {"values": [1, 2], "changes": [{"index": 0, "value": 5}, {"index": 9, "value": 1}]}. The direct version returns ok: false, but values is now [5, 2]: half a batch committed, and the case table's Input kept column says no. The draft version returns the untouched [1, 2].

Exercise

Extend the contract

Reject a change whose value is not a non-negative integer, while preserving the original array on any failure.

Start with the failure: write an input the current code wrongly accepts (a negative or non-numeric value), with the result it should give, and add it to examples.

Edit lib/contract.js, then rerun the original cases. If the requested rule changes an earlier result, update that expected value deliberately. Keep the other cases. Add the acceptance cases to examples so the preview checks them too.

  • Input {"values": [1, 2], "changes": [{"index": 0, "value": -1}]} must return {"ok": false, "values": [1, 2]}.
Your working space Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>Validate a Batch Before Committing It</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run({ values, changes }) { const draft = [...values]; for (const change of changes) { if ( !Number.isInteger(change.index) || change.index < 0 || change.index >= draft.length ) return { ok: false, values }; draft[change.index] = change.value; } return { ok: true, values: draft }; } export const examples = [ [ { values: [1, 2], changes: [ { index: 0, value: 8 }, { index: 9, value: 3 }, ], }, { ok: false, values: [1, 2] }, ], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

Every check that can reject a change must run before that change touches the draft. A bad value is one more reason to reject, exactly like a bad index.

Hint 2: a first step

Check every field before changing the draft at that step.

Show one solution

Replace the exported run function and any constants shown here; keep the examples export underneath it. Compare the result with your own approach.

JavaScript
export function run({ values, changes }) {
  const draft = [...values];
  for (const change of changes) {
    if (
      !Number.isInteger(change.index) ||
      change.index < 0 ||
      change.index >= draft.length ||
      !Number.isInteger(change.value) ||
      change.value < 0
    )
      return { ok: false, values };
    draft[change.index] = change.value;
  }
  return { ok: true, values: draft };
}

The value checks join the index checks in one condition, so a bad value is caught before draft[change.index] is assigned, and the function returns the original values. Number.isInteger rejects 1.5, NaN and the string "3" in one test. Returning the original array, not the half-built draft, is what makes a failure all-or-nothing.

Explain it without the code

Write a batch of three changes where only the last is invalid, and the state a caller should see afterwards.

Going further

Read the Next.js guide for the framework boundary around this rule. The preview runs code-playpad's Next.js simulation. Real caching, hydration, authentication and persistence require the real-server checks described on Day 7.

Was this article helpful?

Your response is saved on this device.