Skip to the code

Create a review with POST

Leaf and Kettle's mobile app lets customers review a tea by sending POST /api/teas/<slug>/reviews with a JSON body like { "rating": 5, "text": "Cool and sweet." }. Write the POST handler in app/api/teas/[slug]/reviews/route.ts. Check the request in this order, and answer the first problem you find.

First the tea: getTea(slug) from @/lib/teas must find it. Otherwise answer 404 with { error: "No tea called coffee" }, with the slug in the message.

Then the format: the Content-Type header must name application/json, in any letter case, optionally followed by parameters like ; charset=utf-8. Otherwise answer 415 with { error: "Send the review as JSON" }.

Then the body must parse as a JSON object. Text that isn't JSON, and JSON that isn't an object (an array, a string, null), get 400 with { error: "The body must be a JSON object" }.

Then the fields. rating must be a whole number from 1 to 5, as a JSON number ("5" in quotes is text), or its message is Rating must be a whole number from 1 to 5. text, with the spaces at its ends removed, must be from 10 to 500 characters long, or its message is Text must be 10 to 500 characters. Answer 400 with { errors }, holding a message for every wrong field.

When everything is right, save { tea, rating, text } with saveReview from @/lib/reviews: the slug from the URL, the rating, and the trimmed text, and nothing else from the body. Answer 201 Created with the review as saved, id included, and a Location header with its URL, /api/teas/<slug>/reviews/<id>.

POST /api/teas/mint/reviews    Content-Type: application/json
{ "rating": 5, "text": "Cool, sweet, and fresh." }
→ 201 { id: 1, tea: "mint", rating: 5, text: "Cool, sweet, and fresh." }
  Location: /api/teas/mint/reviews/1

The app's other files

lib/teas.ts, read-only. Import it as @/lib/teas.

export type Tea = { slug: string; name: string };
 
const teas: Tea[] = [
  { slug: "green", name: "Green tea" },
  { slug: "mint", name: "Mint tea" },
  { slug: "oolong", name: "Oolong tea" },
];
 
/** The tea with this slug, or undefined when the shop doesn't sell it. */
export async function getTea(slug: string): Promise<Tea | undefined> {
  return teas.find((tea) => tea.slug === slug);
}

lib/reviews.ts, read-only. Import it as @/lib/reviews.

export type Review = { id: number; tea: string; rating: number; text: string };
 
/** Every review saved so far. A real shop keeps them in its database. */
export const reviews: Review[] = [];
 
/** Saves a review with the next id, and returns it as saved. */
export async function saveReview(review: Omit<Review, "id">): Promise<Review> {
  const saved = { id: reviews.length + 1, ...review };
  reviews.push(saved);
  return saved;
}

What the tests check

  1. saves a good review and answers 201 with its URL in Location
    const send = (body) =>
      POST(request("/api/teas/mint/reviews", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }), {
        params: params({ slug: "mint" }),
      });
    const response = await send({ rating: 5, text: "Cool, sweet, and fresh." });
    expect(response.status).toBe(201);
    expect(response.headers.get("location")).toBe("/api/teas/mint/reviews/1");
    expect(await response.json()).toEqual({ id: 1, tea: "mint", rating: 5, text: "Cool, sweet, and fresh." });
    const second = await send({ rating: 4, text: "Lovely after dinner." });
    expect(second.headers.get("location")).toBe("/api/teas/mint/reviews/2");
    expect(reviews.map((review) => review.id)).toEqual([1, 2]);
    
  2. saves only the rating and the trimmed text, whatever else the body has
    const body = { rating: 4, text: "   Rich and smooth.  ", id: 99, tea: "green", verified: true };
    const response = await POST(
      request("/api/teas/oolong/reviews", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }),
      { params: params({ slug: "oolong" }) },
    );
    expect(response.status).toBe(201);
    expect(response.headers.get("location")).toBe("/api/teas/oolong/reviews/1");
    expect(reviews).toEqual([{ id: 1, tea: "oolong", rating: 4, text: "Rich and smooth." }]);
    
  3. answers 415 for a body that isn't sent as JSON, and takes a charset
    const send = (type, body) =>
      POST(request("/api/teas/mint/reviews", { method: "POST", headers: { "content-type": type }, body }), { params: params({ slug: "mint" }) });
    const json = JSON.stringify({ rating: 5, text: "Cool, sweet, and fresh." });
    for (const [type, body] of [["text/plain", json], ["application/x-www-form-urlencoded", "rating=5&text=Cool%2C+sweet"], ["application/jsonp", json]]) {
      const response = await send(type, body);
      expect(response.status).toBe(415);
      expect(await response.json()).toEqual({ error: "Send the review as JSON" });
    }
    expect(reviews).toEqual([]);
    expect((await send("application/json; charset=utf-8", json)).status).toBe(201);
    expect((await send("Application/JSON", json)).status).toBe(201);
    
  4. answers 400 for a body that isn't a JSON object
    for (const body of ['{"rating": 5,', "[]", "null", '"Lovely"']) {
      const response = await POST(
        request("/api/teas/mint/reviews", { method: "POST", headers: { "content-type": "application/json" }, body }),
        { params: params({ slug: "mint" }) },
      );
      expect(response.status).toBe(400);
      expect(await response.json()).toEqual({ error: "The body must be a JSON object" });
    }
    expect(reviews).toEqual([]);
    
  5. answers 400 with a message for every wrong field
    const send = async (body) => {
      const response = await POST(
        request("/api/teas/mint/reviews", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }),
        { params: params({ slug: "mint" }) },
      );
      expect(response.status).toBe(400);
      return response.json();
    };
    const rating = "Rating must be a whole number from 1 to 5";
    const text = "Text must be 10 to 500 characters";
    expect(await send({ rating: "5", text: "  Nice     " })).toEqual({ errors: { rating, text } });
    expect(await send({})).toEqual({ errors: { rating, text } });
    for (const value of [0, 6, 4.5, null]) expect(await send({ rating: value, text: "Light and fresh." })).toEqual({ errors: { rating } });
    expect(await send({ rating: 3, text: "a".repeat(501) })).toEqual({ errors: { text } });
    expect(await send({ rating: 3, text: 12345678901 })).toEqual({ errors: { text } });
    expect(reviews).toEqual([]);
    
  6. answers 404 for a tea the shop doesn't sell, before it looks at the body
    const response = await POST(
      request("/api/teas/coffee/reviews", { method: "POST", headers: { "content-type": "text/plain" }, body: "Strong!" }),
      { params: params({ slug: "coffee" }) },
    );
    expect(response.status).toBe(404);
    expect(await response.json()).toEqual({ error: "No tea called coffee" });
    expect(reviews).toEqual([]);
    

Learn more

app/api/teas/[slug]/reviews/route.tsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).