rickwong / fetch-plus Goto Github PK
View Code? Open in Web Editor NEW๐ Fetch API with middlewares
License: BSD 3-Clause "New" or "Revised" License
๐ Fetch API with middlewares
License: BSD 3-Clause "New" or "Revised" License
middleware looks like this:
// json middleware:
(request) => (response) => response.json()
GitHub's fetch polyfill issue:
Draft spec:
Chrome's draft implementation:
How do you keep a consistent cookiejar with this lib?
for instance:
const client = createClient("http://client1.com")
// add middleware
client.addMiddleware(
(request) => {
request.options.headers["Accept"] = "application/json"
request.options.headers["Content-Type"] = "application/json"
request.options.headers["X-Requested-With"] = "XMLHttpRequest"
request.options.credentials = true
return (res) => res.json()
}
)
client.request('/login')
// authentication is lost between these two calls
client.request('/users')
fetch
option is called twice, once from computeObject
and once from the actual request call.
require('fetch-plus').createClient('', {
fetch: () => {
console.log('called');
return { ok: true };
}
}).get('');
Output:
called
called
Hi,
Whenever I pass a text query with spaces, the spaces are replaced with %2520 instead of %20, am I doing something wrong here ?
let q = 'test fetch plus'
endpoint.browse(
URI,
{query: {q}}
)
Request query result : &q=test%2520fetch%2520plus
I do a post to a server and receive a 422 error, the body of the response contains a json object with what validations it failed. However, the docs for fetch indicate that the body of the response hasn't been read at the time of the promise rejection. The body is a ReadableByteStream and the only code I've found to read that is this:
var decoder = new TextDecoder();
var reader = response.body.getReader();
// read() returns a promise that resolves
// when a value has been received
reader.read().then(function processResult(result) {
if (result.done) return;
console.log(
decoder.decode(result.value, {stream: true})
);
// Read some more, and recall this function
return reader.read().then(processResult);
});
The JsonPlus middleware doesn't handle it either. What is the correct way to be able to read the response.json() on a rejected fetch?
Code that may need to change in the fetch-plus source:
http://stackoverflow.com/questions/29473426/fetch-reject-promise-with-json-error-object
Where I found the code to read the body:
https://jakearchibald.com/2016/streams-ftw/
Currently one can't modify request options asynchronously in middleware.
I think all of the following signatures should be supported as middlewares:
Request โ Response โ Response
Request โ Response โ Promise Response
Request โ Promise (Response โ Response)
Request โ Promise (Response โ Promise Response)
To something like createClient()
.
Support for REST entity normalization https://github.com/gaearon/normalizr
Hi,
I followed your boilerplate with the githubApi example but in my case, the api returns a json object {...} instead of an array of objects. It gave me a range error. I think fetch-plus expects an array in the output. Is that true?
const _fetchInitialData = () => {
return myApi.browse(
['posts', '1'], {}
Thanks.
Currently the second argument of a REST action is reserved for query strings object. That's a waste.
If you supply a fetch function via the options argument, it gets called with no arguments when fetchPlus calls computeObject(options)
.
Example:
function myFetch(...args) {
if (args.length === 0) { console.log(" :( "); }
return fetch(...args);
}
const client = createClient("http://localhost", { fetch: myFetch });
client.get("/foo"); // calls myFetch(), then calls myFetch("http://localhost/foo")
In progress
I am getting an error when using the fetch-plus-basicauth module.
I create the import:
import plusBasicAuth from "fetch-plus-basicauth";
then I run:
endpoint.addMiddleware(plusBasicAuth("user", 'API_KEY'));
I get the error:
TypeError: btoa() function required but not available
I have tried installing and importing the npm btoa module (https://www.npmjs.com/package/btoa) but this does not seem to resolve the issue.
https://github.com/sebmck/lerna is much better than npm scripts and (ab)use of concurrently.
I have a url
/api/namespace/{namespace}?query={query}
namespace path param value is AWS/EC2 (please note forward slash '/' in path param)
Now the issue is:
path = normalizeFunc(path.map(compute).map(encodeURI).join("/"));
So this escapes forward-slash, and hence the resulting url from fetch-plus is invalid
/api/namespace/AWS/EC2?query=1
valid path before fetch-plus:
/api/namespace/AWS%2FEC2?query=1
path converted in fetch-plus:
/api/namespace/AWS%252F?query=1
Notice that %2F is converted to %252F which is wrong. This is because of encodeURI.
So we cannot use fetch-plus in this scenario.
Please take a look.
At this moment, createClient only maps BREAD functions like:
endpoint.request = request.bind(null, endpoint);
endpoint.browse = browse.bind(null, endpoint);
endpoint.read = read.bind(null, endpoint);
endpoint.edit = edit.bind(null, endpoint);
endpoint.replace = replace.bind(null, endpoint);
endpoint.add = add.bind(null, endpoint);
endpoint.destroy = destroy.bind(null, endpoint);
We also need to map CRUD functions right?
Monorepo READMEs are difficult to write.
Running this in node v4.4.1
'use strict';
// import {fetch, createClient} from "fetch-plus"
const dp = require('./lib/debug/dumpPromise');
const isomorphicFetch = require('isomorphic-fetch');
const fetchPlus = require('fetch-plus');
const fetch = fetchPlus.fetch;
const createClient = fetchPlus.createClient;
// import plusJson from "fetch-plus-json";
const plusJson = require('fetch-plus-json');//.plusJson;
const api = createClient("http://www.client1.com");
// Add JSON headers and response transformer.
api.addMiddleware(plusJson);
// Add custom error handler that prints and rethrows any error.
api.addMiddleware((request) => ({error: (e) => {console.warn("Rethrowing: ", e&&e.stack||e); throw e;}}));
function renderJSON (response) {
console.log("Rendered response to screen");
console.log(Object.keys(response));
// console.log(JSON.stringify(response,null,4));
}
function renderError (response) {
// console.log();
console.log(JSON.stringify({
'0' : "Rendered Error response to screen",
url:response.url,
status:response.status,
body:((body)=>{
if (typeof body === 'string' )
{
return body.slice(0,160);
}
// return body.read();
// return body.toString();
return {
keys: Object.keys(body),
// prototypeKeys: Object.keys(body.prototype)
};
})(response.body)
},null,4));
console.log(Object.keys(response));
}
const attemptLoginPromise = api.request(["login"], {
method: "POST",
body: {
username: "username",
password: "password",
}
});
attemptLoginPromise.then(renderJSON,renderError);
Rethrowing: TypeError: Cannot read property 'headers' of undefined
at t.before (/home/forge/www/restful/node_modules/fetch-plus-json/dist/index.js:1:707)
at /home/forge/www/restful/node_modules/fetch-plus-json/dist/index.js:1:975
at process._tickCallback (node.js:369:9)
Whenever people write catch (err)
or .catch(err => ...)
they expect err
to be instanceof Error
or at least to have a somewhat similar interface to Error
๐ฆ.
I suggest next major version throws errors with a response
property set to the response which led to error (just like github/fetch suggests) instead of thowing responses.
Support for batching and caching HTTP/REST requests https://github.com/facebook/dataloader
Right now I can not pass FormData if I'm using jsonPlus middleware. All my responses comes as json, so I need to pass Accept header as json as well as parse response.
If I have FormData(want to upload file), I don't need Content-Type: application/json header. fetch-plus-json doesn't handle this case.
Workaround I'm using:
client.addMiddleware((request) => {
if (request.options.body instanceof FormData) {
request.options.headers["Accept"] = "application/json";
return plusJson.handler();
} else {
return plusJson()(request);
}
});
... but .post
, .get
, .patch
, and .del
.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.