Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Introduce fetch API #25

Draft
wants to merge 1 commit into
base: v2.x
Choose a base branch
from
Draft

[WIP] Introduce fetch API #25

wants to merge 1 commit into from

Conversation

veewee
Copy link
Contributor

@veewee veewee commented Sep 14, 2022

Q A
Type feature
BC Break no
Fixed issues

Summary

Sometimes you just want to grab something from the interwebz...
This PR introduces an API similar to Javascript's fetch and shortcut aliases like the axios package.

It is built on top of the transport system, so that you can quickly transform json or deserialize the result into objects.
By default, it uses the new PsrPreset::sync(), which accepts a raw string as data and returns a PSR-7 Response.

Example usage:

$response = fetch('https://swapi.dev/api/people', [
    'headers' => [
        'Accept-Language' => 'nl_BE'
    ],
    'transport' => fn(ClientInterface $client) =>
        JsonPreset::sync($client, RawUriBuilder::createWithAutodiscoveredPsrFactories())
]);

var_dump($response);

Functions:

  • fetch(url[, config])
  • get(url[, config])
  • delete(url[, config])
  • head(url[, config])
  • options(url[, config])
  • post(url[, data[, config]])
  • put(url[, data[, config]])
  • patch(url[, data[, config]])

TODO:

  • Tests
  • Better parameter types for optional data / configs / ...
  • Satic analysis improvements

@pottink
Copy link
Contributor

pottink commented Sep 14, 2022

Nice new feature!

src/Client/FetchClient.php Outdated Show resolved Hide resolved
@veewee veewee force-pushed the fetch-api branch 3 times, most recently from 4651b17 to ad1490d Compare September 19, 2022 06:29
@veewee veewee marked this pull request as draft September 30, 2022 09:22
@veewee
Copy link
Contributor Author

veewee commented Sep 30, 2022

Code works pretty well - but psalm is not able to infer the return types. Making it quite hard to use with psalm currently.
More info:
vimeo/psalm#8487

Alternative is to work with mixed types instead and let upstream deal with figuring out the types - which is not really how I'dd like this to work.

Keeping this one as-is for now!

@janvernieuwe
Copy link
Member

Nice feature!
As a user you could prep a SerializerTransport and just define the output with each call too, eliminating the need to make one for each return type. Though It might break autocompletion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants