Below is a sample implementation for Creating a Task. We're taking an iterative approach, where we define the Request and Response classes with the handler at first.
- Use the Model code snippets
- Create a file under apps/api/Tasks/Create.ts
- Create a
Request
class:
export class CreateRequest extends Post("/tasks")<Create>()({
listId: prop(TaskListIdU),
title: prop(nonEmptyString),
isFavorite: prop(bool),
myDay: prop(optionFromNull(date)),
}) {}
- Create a
Response
class, if the Response is something else thanvoid
:
export class Response extends Model<Response>()({ id: prop(TaskId) }) {}
- Create the Handler (omit
Response
if you didn't create one)
export default handle({ Request, Response })(
// (Request) => T.Effect<Has<UserProfile> & Has<TodoContext.TodoContext>, NotFoundError | UnauthorizedError | NotLoggedInError, Response>
({ myDay, ...input }) =>
T.gen(function* ($) {
const { Lists, Tasks, Users } = yield* $(TodoContext.TodoContext)
const user = yield* $(TodoContext.getLoggedInUser)
if (input.listId !== "inbox") {
const list = yield* $(Lists.getList(input.listId))
yield* $(TaskListAuth.access_(list, user.id, identity))
}
const task = User.createTask._(user, input)
yield* $(Tasks.add(task))
yield* $(
pipe(
EO.fromOption(myDay),
EO.chainEffect((date) => Users.update(user.id, User.addToMyDay(task, date)))
)
)
return { id: task.id }
})
)
- Add to routes.ts routes tuple:
R.match(Create, demandLoggedIn)
fromimport Create from "./Create"
Test api and enjoy. Find autogenerated openapi.json or visit the local swagger
- Move
Request
andResponse
to packages/client/Tasks/Create.ts - Export in _index.ts:
export * as Create from "./Create"
- Update the handler in api:
export default handle(Tasks.Create)
-
Add the
create
to theexport const {
in client/Tasks/index.ts -
Use
// (req: Tasks.Create.CreateTask) => T.Effect<Has<TodoClient.ApiConfig> & Has<Http>, FetchError | ResponseError, Tasks.CreateTask.Response>
TodoClient.Tasks.create
e.g:
const { runWithErrorLog } = useServiceContext()
TodoClient.Tasks.create(input)
["|>"](runWithErrorLog)
Note: if there is no input required, the signature is just an Effect:
// T.Effect<Has<TodoClient.ApiConfig> & Has<Http>, FetchError | ResponseError, TodoClient.Tasks.All.Response>
TodoClient.Tasks.all
which would be used so:
const { runWithErrorLog } = useServiceContext()
TodoClient.Tasks.all
["|>"](runWithErrorLog)