Created
December 15, 2021 15:19
-
-
Save ryanflorence/859e39736a77465f9f2da2f8d3c9d584 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export let action: ActionFunction = async ({ request, params }) => { | |
let session = await requireAuthSession(request); | |
await ensureUserAccount(session.get("auth")); | |
let data = Object.fromEntries(await request.formData()); | |
invariant(typeof data._action === "string", "_action should be string"); | |
switch (data._action) { | |
case Actions.CREATE_TASK: | |
case Actions.UPDATE_TASK_NAME: { | |
invariant(typeof data.id === "string", "expected taskId"); | |
invariant(typeof data.name === "string", "expected name"); | |
invariant( | |
typeof data.date === "string" || data.date === undefined, | |
"expected name" | |
); | |
return createTask(data.id, data.date) | |
} | |
case Actions.MARK_COMPLETE: { | |
invariant(typeof data.id === "string", "expected task id"); | |
return markComplete(data, id) | |
} | |
case Actions.MARK_INCOMPLETE: { | |
invariant(typeof data.id === "string", "expected task id"); | |
return markIncomplete(data.id) | |
} | |
case Actions.MOVE_TASK_TO_DAY: { | |
invariant(typeof data.id === "string", "expected taskId"); | |
invariant(params.day, "expcted params.day"); | |
return moveTaskToDay(data.id, params.day) | |
} | |
case Actions.MOVE_TASK_TO_BACKLOG: { | |
invariant(typeof data.id === "string", "expected taskId"); | |
return moveTaskToBacklog(data.id, params.day) | |
} | |
case Actions.DELETE_TASK: { | |
invariant(typeof data.id === "string", "expected taskId"); | |
return deleteTask(data.id) | |
} | |
default: { | |
throw new Response("Bad Request", { status: 400 }); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is unfinished but is a starting point of where I would handle the logic of validation separately from the place where it's executed in the controller.
That way I would be able to write tests for each validation rule, probably one "name" per need instead of per field name and type.
Also, I'd leverage a bit more user-defined assertion functions.
I would start with something like the following
The controller file
Then, in the switch map, you can do
Refer to:
Note that this is just a quick draft, I've litterally spent less than an hour just to see how I would write validation in a way where I'd be able to write tests without testing the controller and the data passing into it. This was just a kata to flex my muscles, I would probably do more but that was just for illustration. Clearly there has to have more validator because data types, while it is best to have flat structure, are rarely just strings numbers, boolean etc.