Skip to content
This repository was archived by the owner on Jan 5, 2023. It is now read-only.

Latest commit

 

History

History
92 lines (77 loc) · 2.94 KB

Creating_a_usecase.md

File metadata and controls

92 lines (77 loc) · 2.94 KB

Creating a Usecase

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.

Tips

API

  1. Create a file under apps/api/Tasks/Create.ts
  2. Create a Request class:
export class CreateRequest extends Post("/tasks")<Create>()({
  listId: prop(TaskListIdU),
  title: prop(nonEmptyString),
  isFavorite: prop(bool),
  myDay: prop(optionFromNull(date)),
}) {}
  1. Create a Response class, if the Response is something else than void:
export class Response extends Model<Response>()({ id: prop(TaskId) }) {}
  1. 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 }
  })
)
  1. Add to routes.ts routes tuple: R.match(Create, demandLoggedIn) from import Create from "./Create"

Test api and enjoy. Find autogenerated openapi.json or visit the local swagger

Update Client for Frontend

  1. Move Request and Response to packages/client/Tasks/Create.ts
  2. Export in _index.ts: export * as Create from "./Create"
  3. Update the handler in api: export default handle(Tasks.Create)

Consume in Frontend

  1. Add the create to the export const { in client/Tasks/index.ts

  2. 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)