Skip to content

Commit

Permalink
Some more work on handlePost
Browse files Browse the repository at this point in the history
  • Loading branch information
enjikaka committed Jan 10, 2024
1 parent 817a2b9 commit bf0a88a
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 3 deletions.
18 changes: 17 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down Expand Up @@ -58,18 +63,29 @@ export class Rutabaga {

/**
* @param {Object} object
* @returns {boolean}
*/
validate(object) {
return this.#validate(object);
}

/**
* @param {Request} request
* @returns {Response}
* @returns {Promise<Response>}
*/
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
});
}
}
45 changes: 43 additions & 2 deletions src/index.test.js
Original file line number Diff line number Diff line change
@@ -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",
Expand Down Expand Up @@ -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);
});
});

0 comments on commit bf0a88a

Please sign in to comment.