<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Muhammad Fuad Ardiono</title>
    <description>The latest articles on Forem by Muhammad Fuad Ardiono (@fuadardiono).</description>
    <link>https://forem.com/fuadardiono</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F369466%2Fdc2b771f-df9a-427a-bca7-b8c51ec493b9.jpeg</url>
      <title>Forem: Muhammad Fuad Ardiono</title>
      <link>https://forem.com/fuadardiono</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/fuadardiono"/>
    <language>en</language>
    <item>
      <title>Create scaleable HTTP Client with Typescript and Fetch API</title>
      <dc:creator>Muhammad Fuad Ardiono</dc:creator>
      <pubDate>Wed, 07 Jun 2023 09:55:05 +0000</pubDate>
      <link>https://forem.com/fuadardiono/create-scaleable-http-client-with-typescript-and-fetch-api-2ckj</link>
      <guid>https://forem.com/fuadardiono/create-scaleable-http-client-with-typescript-and-fetch-api-2ckj</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnutemvphmdb4nlp0ibun.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnutemvphmdb4nlp0ibun.png" alt="Typescript Lang"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Using third-party libraries might make development faster or easier. As an engineer, you need to think about how to manage the bundle size of an application, especially if the application is a client side application example case such as React, Vue, Svelte, Angular project and etc. A heavy bundle size will slow down the web page load time.&lt;/p&gt;

&lt;p&gt;In this article we will create an HTTP Client using Typescript and Fetch API. The HTTP Client can adjust to the needs of the product to be developed. Real-life example of client side calling API from server A, server B, server C and etc. From each API that is called has a different header such as the header signature requirement. How do we manage it? We create own HTTP client can adapt the product requirement, so we can create HTTPClientAPIA, HTTPClientAPIB, HTTPClientAPIC, and etc.&lt;/p&gt;

&lt;h2&gt;
  
  
  RESULT &amp;amp; DESIGN
&lt;/h2&gt;

&lt;p&gt;We create an enum HttpClientBaseMethod, we will use that every time we make a request to the API. So what request method code we write, will be safe from typo and more consistent we call POST with value ‘POST’ not ‘post’. We create enum of HttpStatusCode to cast response value status code from Fetch API. We create a standard base header, and standard base status code of our HTTPClient. Why need standard? because we want our code consistent.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

export enum HttpClientBaseMehod {
    POST = 'POST',
    GET = 'GET',
    PUT = 'PUT'
}

export interface HttpClientBaseHeader {
    'Content-Type': string,
    'Authorization'?: string
}

export interface HttpClientBaseStatusCode {
    statusCode: number
    statusText: HttpStatusCode
}

export enum HttpStatusCode {
    Continue = 100,
    SwitchingProtocols = 101,
    Processing = 102,
    Ok = 200,
    Created = 201,
    Accepted = 202,
    NonAuthoritativeInformation = 203,
    NoContent = 204,
    ResetContent = 205,
    PartialContent = 206,
    MultiStatus = 207,
    AlreadyReported = 208,
    ImUsed = 226,
    MultipleChoices = 300,
    MovedPermanently = 301,
    Found = 302,
    SeeOther = 303,
    NotModified = 304,
    UseProxy = 305,
    SwitchProxy = 306,
    TemporaryRedirect = 307,
    PermanentRedirect = 308,
    BadRequest = 400,
    Unauthorized = 401,
    PaymentRequired = 402,
    Forbidden = 403,
    NotFound = 404,
    MethodNotAllowed = 405,
    NotAcceptable = 406,
    ProxyAuthenticationRequired = 407,
    RequestTimeout = 408,
    Conflict = 409,
    Gone = 410,
    LengthRequired = 411,
    PreconditionFailed = 412,
    PayloadTooLarge = 413,
    UriTooLong = 414,
    UnsupportedMediaType = 415,
    RangeNotSatisfiable = 416,
    ExpectationFailed = 417,
    IAmATeapot = 418,
    MisdirectedRequest = 421,
    UnprocessableEntity = 422,
    Locked = 423,
    FailedDependency = 424,
    UpgradeRequired = 426,
    PreconditionRequired = 428,
    TooManyRequests = 429,
    RequestHeaderFieldsTooLarge = 431,
    UnavailableForLegalReasons = 451,
    InternalServerError = 500,
    NotImplemented = 501,
    BadGateway = 502,
    ServiceUnavailable = 503,
    GatewayTimeout = 504,
    HttpVersionNotSupported = 505,
    VariantAlsoNegotiates = 506,
    InsufficientStorage = 507,
    LoopDetected = 508,
    NotExtended = 510,
    NetworkAuthenticationRequired = 511,
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Then we create the class HTTPClientBase and wrapping Fetch API. You can read the documentation of Fetch API &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Because our main goal is to make an HTTPClient that can be easily scaled, and extend. So we wrap it to the class.&lt;/p&gt;

&lt;p&gt;If we don’t wrap the Fetch API with class it will make our code messy, hard to read, hard to scale. Why? Imagine if we just use Fetch API then our source code is big and growing and someday we need refactor the API call from server C to add/change the header or different mechanism to call API that would be a disaster of refactoring. It will take a long time, whereas if we use an agile software methodology it takes a short time in development and release.&lt;/p&gt;

&lt;p&gt;`export class HttpClientBase {&lt;br&gt;
    private resp: Response&lt;br&gt;
    private respBody: any&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async createRequest(
    url: string,
    method: HttpClientBaseMehod,
    httpHeader?: HttpClientBaseHeader,
    requestData?: any
): Promise&amp;lt;this&amp;gt; {
    const requestInit: RequestInit = {
        method
    }

    if (httpHeader) {
        requestInit.headers = httpHeader as any
    }

    if (requestData) {
        requestInit.body = JSON.stringify(requestData)
    }

    this.resp = await fetch(url, requestInit)
    this.respBody = await this.resp.json()

    return this
}

statusCode(): HttpClientBaseStatusCode {
    const statusCode = this.resp.status as HttpStatusCode
    const statusText = HttpStatusCode[this.resp.status] as unknown as HttpStatusCode

    return {
        statusCode,
        statusText
    }
}

isOk(): boolean {
    return this.resp.ok
}

responseByKey&amp;lt;T&amp;gt;(key: string | null = null): T {
    if (key) {
        return this.respBody[key]
    } else {
        return this.respBody
    }
}

responseData&amp;lt;T&amp;gt;(): T {
    return this.respBody.data
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}`&lt;/p&gt;

&lt;p&gt;createRequest is function creating/build the request to Fetch API. We have wrap Fetch API to that function.&lt;/p&gt;

&lt;p&gt;statusCode is function casting status code value from Fetch API to our standard HttpClient.&lt;/p&gt;

&lt;p&gt;isOk is function wrapping the value condition of the request from Fetch API.&lt;/p&gt;

&lt;p&gt;responseByKey is a function that we can use to extract response by key JSON value from the API server.&lt;/p&gt;

&lt;p&gt;responseData is a function to return the data by key JSON ‘data’ of response.&lt;/p&gt;

&lt;p&gt;We use Generic Type at function responseByKey and responseData because we want our code know what the API server response. We need write the Data Transfer Object (DTO) every response we have get.&lt;/p&gt;

&lt;p&gt;Header type can be extend with or (|) type you can extend the type of header just adjust what you need.&lt;/p&gt;

&lt;h2&gt;
  
  
  IMPLEMENTATION &amp;amp; CASE STUDY
&lt;/h2&gt;

&lt;p&gt;We will implement HTTPClient we have create, with case study of &lt;a href="https://jsonplaceholder.typicode.com/" rel="noopener noreferrer"&gt;JSONPlaceholder&lt;/a&gt; API. Here is code sandbox &lt;a href="https://codesandbox.io/s/ts-httpclient-fetch-api-beze7p" rel="noopener noreferrer"&gt;https://codesandbox.io/s/ts-httpclient-fetch-api-beze7p&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  REFFERENCE
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://gist.github.com/RWOverdijk/6cef816cfdf5722228e01cc05fd4b094" rel="noopener noreferrer"&gt;Http Status Code Gist&lt;/a&gt;&lt;br&gt;
&lt;a href="https://refactoring.guru/design-patterns/builder" rel="noopener noreferrer"&gt;https://refactoring.guru/design-patterns/builder&lt;/a&gt;&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>fetchapi</category>
      <category>httpclient</category>
      <category>programming</category>
    </item>
    <item>
      <title>Plain old PHP Object - Usability and benefits in modern PHP programming</title>
      <dc:creator>Muhammad Fuad Ardiono</dc:creator>
      <pubDate>Tue, 21 Apr 2020 05:48:15 +0000</pubDate>
      <link>https://forem.com/fuadardiono/plain-old-php-object-usability-and-benefits-in-modern-php-programming-32oc</link>
      <guid>https://forem.com/fuadardiono/plain-old-php-object-usability-and-benefits-in-modern-php-programming-32oc</guid>
      <description>&lt;p&gt;If you familiar with Java, maybe you already known about POJO (Plain Old Java Object). Because the term of POJO first coined by Martin Fowler, Rebecca Parsons and Josh MacKenzie on Java programming language in 2000. POJO gives us ease in understanding the types of data structures that are in a class object.&lt;/p&gt;

&lt;h1&gt;
  
  
  We have the case:
&lt;/h1&gt;

&lt;ol&gt;
&lt;li&gt;So what is the name of POJO in another programming language? &lt;/li&gt;
&lt;li&gt;Why we need DTO in modern PHP programming?&lt;/li&gt;
&lt;li&gt;How to make DTO in modern php programming?&lt;/li&gt;
&lt;li&gt;How to implement DTO in modern PHP programming?&lt;/li&gt;
&lt;/ol&gt;

&lt;h1&gt;
  
  
  Answer the case:
&lt;/h1&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;So what is the name of POJO in another programming language?&lt;br&gt;
The convention about Plain Old Object is "Plain Old programming_language_name Object". So if you on Ruby, you can call PORO (Plain Old Ruby Object) maybe Rubyist already known about it. If on PHP it's called POPO (Plain Old PHP Object). Every language can implement Plain Old Object if they have a class, or in modern way you can call it DTO.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Why DTO in modern PHP programming?&lt;br&gt;
DTO can guide us about data structure, and give us clarity about what the type data on that object. You can create DTO (Data Transfer Object) inside of DTO, example guide: "toArray()", "castToClass()", "toJSON()" something like that. So you carries the data or value not in variable, but on class object based. It can gives you standardisation about how to communicate from object A to object B. And give you less function paramater, you just pass with DTO class. In modern PHP programming web application we often use MVC (Model, View, Controller) then it will have often communication each object. From controller to service, controller get data return from service, and return to view. With DTO we can make better communication each object.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;How to make DTO in PHP programming?&lt;br&gt;
You can make DTO by define what the class?, what the property? and then you can make it. DTO should have setters and getters. First things we define the class, Food have property name, price, quantity, and total price. Then we can set the value by setter function on Food DTO. If we want transform it to JSON we can call "toJSON()" function and etc. You can develop according to what you need. Example guide:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--sZ7UiKun--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://i.imgur.com/nBP4FK9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--sZ7UiKun--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://i.imgur.com/nBP4FK9.png" alt="DTO image" width="631" height="1591"&gt;&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;How to implement DTO in modern PHP programming?&lt;br&gt;
You can start it by creating new DTO. In above example, we can call with php syntax "new Food()".&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Example 1 (Simple Controller):&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--OTHSH3Iq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://i.imgur.com/zfvZFnw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--OTHSH3Iq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://i.imgur.com/zfvZFnw.png" alt="Example 1" width="800" height="655"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In example 1 we use toArray() to communicate to Model.&lt;/p&gt;

&lt;p&gt;Example 2 (Controller, Service and Model):&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--XJjmgUbE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://i.imgur.com/YgjERw9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--XJjmgUbE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://i.imgur.com/YgjERw9.png" alt="Example 2 controller" width="800" height="493"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We pass class object to service&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--B2OPpo4s--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://i.imgur.com/olDkxrq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--B2OPpo4s--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://i.imgur.com/olDkxrq.png" alt="Example 2 service" width="800" height="706"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We use toArray() to communicate to Model.&lt;/p&gt;

&lt;p&gt;On below with no DTO our function store on food service is looked not maintainable, too much parameter.&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--V5gVBZ8O--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://i.imgur.com/N7lZjy3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--V5gVBZ8O--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://i.imgur.com/N7lZjy3.png" alt="Bad code" width="800" height="532"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;That is a little quick implementation DTO in modern PHP. You can use DTO for simplify your parameter function and you can get better communication each object or class. You can explore more and implement to your own development according what you need. Any question, feel free to comment on below. Happy code!!&lt;/p&gt;

&lt;h1&gt;
  
  
  Reference
&lt;/h1&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Plain_old_Java_object"&gt;Plain old Java Object&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Data_transfer_object"&gt;Data Transfer Object&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>php</category>
      <category>refactorit</category>
      <category>laravel</category>
      <category>backend</category>
    </item>
  </channel>
</rss>
