Handling an API request to Get Popular Posts

Similar to last time, we can handle the request through either a RESTful API controller or a GraphQL resolver.

Here's an example of a RESTful API controller that handles the request. The GetPopularPostsRequestDTO type describes anything we'd like to use as an input to the GetPopularPosts use case.

// useCases/getPopularPosts/GetPopularPostsController.ts

export class GetPopularPostsController extends BaseController {
  private useCase: GetPopularPosts;

  constructor (useCase: GetPopularPosts) {
    this.useCase = useCase;

  async executeImpl (req: DecodedExpressRequest, res: express.Response): Promise<any> {

    const dto: GetPopularPostsRequestDTO = {
      offset: req.query.offset

    try {
      const result = await this.useCase.execute(dto);

      if (result.isLeft()) {
        const error = result.value;
        switch (error.constructor) {
            return this.fail(res, error.errorValue().message);
      } else {
        const postDetails = result.value.getValue();
        return this.ok<GetPopularPostsResponseDTO>(res, {
          posts: postDetails.map((d) => PostDetailsMap.toDTO(d))

    } catch (err) {
      return this.fail(res, err)

The response type of this DTO looks like the following.

// post/dtos/GetPopularPostsResponseDTO.ts

import { PostDTO } from "../../../dtos/postDTO";

export interface GetPopularPostsResponseDTO {
  posts: PostDTO[];

Continue reading

Howdy 👋

This is an online wiki and book about the basics of software design and architecture with TypeScript by Khalil Stemmler, Developer Advocate @ Apollo GraphQL .

This book’s mission is to teach developers the essential skills and practices to write testable, flexible, and maintainable code.

You can read more about the learning journey in the "Software Design and Architecture Roadmap 🖼️".

Already bought it?

If you’ve already purchased the book, click here to re-send your link. You can read the online wiki or download a copy of the book in PDF, EPUB, and Kindle versions.

Want access?

You can read the intro to the book for free and visit solidbook.io to buy the book/wiki (it's currently on pre-sale for 33% off)! For recent updates, click here. To get an idea of my writing, read some of my best free content here and here.

Need help?

Something not working? Have a question? You can reach me on Twitter or khalil@khalilstemmler.com.