From bf0a88aa79210d7fbf054b596f28dd66e129bd53 Mon Sep 17 00:00:00 2001 From: Jeremy Karlsson Date: Wed, 10 Jan 2024 19:10:20 +0100 Subject: [PATCH] Some more work on handlePost --- src/index.js | 18 +++++++++++++++++- src/index.test.js | 45 +++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 60 insertions(+), 3 deletions(-) diff --git a/src/index.js b/src/index.js index 23f9dbc..35a22d5 100644 --- a/src/index.js +++ b/src/index.js @@ -2,6 +2,11 @@ import Ajv from "ajv"; import { Dexie } from "dexie"; import { convertFormDataToObject } from "./helpers/convertFormDataToObject.js"; +const httpStatusCodes = { + CREATED: 201, + BAD_REQUEST: 402, +}; + // @ts-ignore const ajv = new Ajv(); @@ -58,6 +63,7 @@ export class Rutabaga { /** * @param {Object} object + * @returns {boolean} */ validate(object) { return this.#validate(object); @@ -65,11 +71,21 @@ export class Rutabaga { /** * @param {Request} request - * @returns {Response} + * @returns {Promise} */ async handlePost(request) { const formData = await request.formData(); const obj = convertFormDataToObject(formData); + if (!this.validate(obj)) { + return new Response(null, { + status: httpStatusCodes.BAD_REQUEST, + statusText: `The provided form data did not validate against the schema "${this.#schemaName}". ${JSON.stringify(this.#schema)}` + }); + } + + return new Response(null, { + status: httpStatusCodes.CREATED + }); } } diff --git a/src/index.test.js b/src/index.test.js index 3538a41..5b65b89 100644 --- a/src/index.test.js +++ b/src/index.test.js @@ -1,6 +1,6 @@ -import { Dexie, Table } from "dexie"; +import { Dexie } from "dexie"; import { expect, test, describe } from "vitest"; -import { Rutabaga } from "./index"; +import { Rutabaga } from "./index.js"; const jsonSchemaExample = { title: "Person", @@ -62,3 +62,44 @@ describe('database', () => { expect(rutabaga.table).not.toBe(undefined); }); }); + +describe('handlePost', () => { + const db = new Dexie(dataBaseName); + + test("returns 402 if form data is malformed", async () => { + const rutabaga = new Rutabaga(jsonSchemaExample, dataBaseName); + + const formData = new FormData(); + + formData.append('middleName', 'John'); + formData.append('age', '21'); + + const request = new Request('http://localhost:1234', { + method: 'POST', + body: formData + }); + + const response = await rutabaga.handlePost(request); + + expect(response.status).toBe(402); + }); + + test("returns 201 if form data is accepted and added to the database", async () => { + const rutabaga = new Rutabaga(jsonSchemaExample, dataBaseName); + + const formData = new FormData(); + + formData.append('firstName', 'John'); + formData.append('lastName', 'John'); + formData.append('age', '21'); + + const request = new Request('http://localhost:1234', { + method: 'POST', + body: formData + }); + + const response = await rutabaga.handlePost(request); + + expect(response.status).toBe(201); + }); +});