Api service implementation

We start by focusing on the server implementation and ignore the client for now.

We can treat the server as a normal Node.js backend application. We can define services that read from the file system, query databases, make HTTP requests, and more.

For each route we then create a server component that composes the services, executes the final effect, and renders the page.

API service definition

In this example we define a server-only API that makes requests to jsonplaceholder.

We create a new Api.ts file inside services. Inside it, we implement the service using Effect.Service:

Learn more about Effect.Service here: Effect.Service: Service and Layer all in one

src/services/Api.ts
import { Effect } from "effect";

export class Api extends Effect.Service<Api>()("Api", {
  // ...
}) {}

Api will contain all the methods that we need to make requests to the jsonplaceholder API:

  • getPosts: fetches an array of posts
  • getPostById: fetches a single post by id

Before we can implement these methods, we first define a HttpClient that will be used to make requests to the API.

Let's do this next.