0

When I read this HTTP Client Manager docs on Drupal, I don't understand why it returns the $build when $request->getStatusCode() == 200, is that supposed to be not equal 200? I also copy and paste the code from Drupal docs.

public function posts($limit, $sort) {
    $build = [
      '#theme' => 'mymodule_posts_list',
      '#posts' => [],
    ];

    $request = $this->httpClient->request('GET', 'http://api.example.com/posts', [
      'limit' => $limit,
      'sort' => $sort,
    ]);

    // This is the Part I don't understand.
    if ($request->getStatusCode() == 200) {
      return $build;
    }

    $posts = $request->getBody()->getContents();
    foreach ($posts as $post) {
      $build['#posts'][] = [
        'id' => $post['id'],
        'title' => $post['title'],
        'text' => $post['text'],
      ];
    }
    return $build;
  }
  • I suspect that the condition here should be != 200... e.g. return an empty array of posts if the api does not get a valid response. – CG Monroe Jun 14 at 16:18
  • Thank you, CG Monroe – Jiang Zhan Jun 14 at 16:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.