MCPcopy
hub / github.com/wendux/fly

github.com/wendux/fly @main sqlite

repository ↗ · DeepWiki ↗
120 symbols 240 edges 29 files 6 documented · 5%
README

fly.js

npm version build status coverage size platform

Fly.js

Supporting request forwarding and Promise based HTTP client for all JavaScript runtimes.

Chinese documentation : 中文文档

Browser Support

Chrome Firefox Safari Opera Edge IE
> 8

Other Platforms Support

node logo Mini Program logo mpvue logo weex logo quick app logo

Currently the platforms that fly.js supported include Node.jsWeChat Mini ProgramWeexReact NativeQuick App and the browers, all JavaScript runtimes of these are different. More platforms are supporting...

Features

  1. Supports the Promise API
  2. Make XMLHttpRequests from the browser,light-weight and very light-weight
  3. Supports various JavaScript runtimes
  4. Supports request and response interceptors。
  5. Automatic transforms for JSON data。
  6. Supports switching the underlying Http Engine, easy to adapt to various JavaScript Runtime.
  7. Supports global Ajax interception on browser
  8. Supports request forwarding in hybrid applications

Positioning & target

Fly.is locates to be the ultimate solution for Javascript http requests. That is to say, in any environment that can execute Javascript, as long as it has the ability to access the network, Fly can run on it and provide unified APIs. At the same time, keep lightweight on the browser side.

Documentation

You can find the Fly documentation on the offical website.

中文文档

Installing

Using npm

npm install flyio

Using CDN (on browsers)

<script src="https://cdn.jsdelivr.net/npm/flyio/dist/fly.min.js"></script>

UMD (on browsers)

https://cdn.jsdelivr.net/npm/flyio/dist/umd/fly.umd.min.js

Require flyio

The entry files of different JavaScript Runtimes may be different, you can refer on the below, but the entries of Browsers, Node, and React Native are the same。each requirement ways of these platforms are as follows:

  1. Requiring On browsers、Node、React Native

javascript //for Browsers, Node, and React Native var fly=require("flyio")

The above method requires the default instance of Fly, and you can also create an Fly instance by yourself:

javascript // for browsers and React Native var Fly=require("flyio/dist/npm/fly") // for Node //var Fly=require("flyio/src/node") var fly=new Fly;

  1. Requiring on WeChat Mini Program

javascript var Fly=require("flyio/dist/npm/wx") var fly=new Fly

If your project does not use NPM to manage dependencies, you can download the source code directly to your project 。The download links are wx.js or wx.umd.min.js . Download any one, save it to your project directory (assuming named "lib") , and then requiring:

javascript var Fly=require("../lib/wx") var fly=new Fly;

  1. Requiring on Quick App

On Quick App, Fly relies on the fetch module, which needs to be defined in the manifest.json first:

java "features": [ ... {"name": "system.fetch"} ]

And then create Fly instance:

javascript var fetch = require("@system.fetch") var Fly=require("flyio/dist/npm/hap") var fly=new Fly(fetch)

  1. Requiring on Weex

javascript var Fly=require("flyio/dist/npm/weex") var fly=new Fly

After the requirement, you can make the global configuration and add the interceptor to fly , and peform network request with fly.

Example

The following example, if not specified, can be executed in all JavaScript Runtimes.

Performing a GET request

var fly=require("flyio")
// Make a request for a user with a given ID,  and the parameter is passed directly in URL
fly.get('/user?id=133')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// The parameter is passed by a object
fly.get('/user', {
      id: 133
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Performing a POST request

fly.post('/user', {
    name: 'Doris',
    age: 24
    phone:"18513222525"
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

POST request with Url params

fly.get("../package.json", "xxx=5", {
        params: {
            c: 1
        }
    }
)

The final url is "package.json?c=1&xxx=5".

Performing multiple concurrent requests

function getUserRecords() {
  return fly.get('/user/133/records');
}

function getUserProjects() {
  return fly.get('/user/133/projects');
}

fly.all([getUserRecords(), getUserProjects()])
  .then(fly.spread(function (records, projects) {
    // Both requests are now complete
  }))
  .catch(function(error){
    console.log(error)
  })

Performing the request by request

fly.request("/test",{hh:5},{
    method:"post",
    timeout:5000 // Set timeout to 5 seconds
 })
.then(d=>{ console.log("request result:",d)})
.catch((e) => console.log("error", e))

Sending URLSearchParams

const params = new URLSearchParams();
params.append('a', 1);
fly.post("",params)
.then(d=>{ console.log("request result:",d)})

Note that URLSearchParams is not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment).

Sending FormData

 var formData = new FormData();
 var log=console.log
 formData.append('username', 'Chris');
 fly.post("../package.json",formData).then(log).catch(log)

Note that FormData is not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment). And there are some differences on the way to support formData in node environment. Please click here for more details

Requesting Stream

fly.get("/Fly/v.png",null,{
    responseType:"arraybuffer"
}).then(d=>{
  //d.data is a ArrayBuffer instance
})

In browser, the value of responseType can be one of "arraybuffer" or "blob". In node, you can just set it as "stream"

interceptors

You can intercept requests or responses before they are handled by then or catch.


// Add a request interceptor
fly.interceptors.request.use((request)=>{
    // Do something before request is sent
    request.headers["X-Tag"]="flyio";
    console.log(request.body)
    // Complete the request with custom data
    // return Promise.resolve("fake data")
})

// Add a response interceptor
fly.interceptors.response.use(
    (response) => {
      // Do something with response data .
      // Just return the data field of response
      return response.data
    },
    (err) => {
      // Do something with response error
      //return Promise.resolve("ssss")
    }
)

The structures of the request object in request interceptor.

{
  baseURL,  //base url
  body, // request parameters
  headers, //custom request headers
  method, // http request method
  timeout, // request time
  url, // request url (or relative path)
  withCredentials, // determine whether sending thirdparty cookies in cross-domain request
  ... // custom field defined in options
}

The structures of the response object in response interceptor.

{
  data, //response data
  engine, //http engine,In browser,it's a instance of XMLHttpRequest.
  headers, //response headers
  request  //the origin request object
}

Remove interceptors

If you may need to remove an interceptor later, just set it to null.

fly.interceptors.request.use(null)
fly.interceptors.response.use(null,null)

Perform an async task in interceptors

Now, you can perform async task in interceptors !

Let's see an example:

because of security reasons, we need all the requests to set up a csrfToken in the header, if csrfToken does not exist, we need to request a csrfToken first, and then perform the network request, because the request csrfToken progress is asynchronous, so we need to execute this async request in request interceptor. the code is as follows:

var csrfToken="";
var tokenFly=new Fly();
var fly=new Fly();
fly.interceptors.request.use(function (request) {
    //if csrfToken does not exist, we need to request a csrfToken first
    if(!csrfToken) {
         // locking the current instance, let the incomming request task enter a 
         // queue before they enter the request interceptors.
         fly.lock();
         //Using  another fly instance to request csrfToken.
         //If use the same fly instance, there may lead a infinite loop:
         //(The request will go to the interceptor first, and then
         //enter the interceptor again when launching the new request 
         //in the interceptor....)
         return tokenFly.get("/token").then((d)=>{
            request.headers["csrfToken"]=csrfToken=d.data.data.token;
            //only return the origin `request` object can make the http request continue.
            // otherwise, the return data will be teated as "response" data.
            return request 
          }).finally(()=>{
           //fly.clear(); //clear the request queue
           // unlock the current instance, flush the request queue.   
           fly.unlock()
         })  

    }else {
        request.headers["csrfToken"]= csrfToken;
        //This line can be omitted. 
        //If the interceptor doesn't return value, `request` will be used by default.
        return request 
    }
})

Note:

  1. The current fly instance will be locked when call fly.lock() . Once the fly instance is locked, the incomming request task maked by it will be hang up and enter a queue before they enter the request interceptors, you can call fly.unlock() to continue the requests or call fly.clear() to cancel the requests in the queue.
  2. Only when you return the request object passed by interceptor at the final , the origin http request will be continued.

And you can also make an async task in the response interceptor. More information about interceptors and examples refer to flyio interceptor.

Extension points exported contracts — how you extend this code

FlyRequestInterceptor (Interface)
(no doc) [2 implementers]
index.d.ts
FlyResponseInterceptor (Interface)
(no doc) [2 implementers]
index.d.ts
FlyRequestConfig (Interface)
(no doc)
index.d.ts
FlyError (Interface)
(no doc)
index.d.ts
FlyResponse (Interface)
(no doc)
index.d.ts

Core symbols most depended-on inside this repo

_call
called by 24
src/engine-wrapper.js
_changeReadyState
called by 15
src/engine-wrapper.js
get
called by 11
index.d.ts
onerror
called by 11
miniprogram_dist/index.js
getResponseHeader
called by 9
src/engine-wrapper.js
encode
called by 9
src/utils/utils.js
getAndDelete
called by 8
miniprogram_dist/index.js
request
called by 7
index.d.ts

Shape

Method 63
Function 43
Interface 8
Class 6

Languages

TypeScript100%

Modules by API surface

index.d.ts28 symbols
src/fly.js18 symbols
_.js18 symbols
miniprogram_dist/index.js17 symbols
src/engine-wrapper.js14 symbols
src/utils/utils.js8 symbols
miniprogram_dist/engine-wrapper.js8 symbols
src/node/index.js2 symbols
src/adapter/wx.js2 symbols
src/adapter/webviewjsbridge.js2 symbols
src/adapter/ap.js2 symbols
test/test.js1 symbols

Dependencies from manifests, versioned

babel-core6.0.0 · 1×
babel-loader6.0.0 · 1×
babel-plugin-transform-runtime6.0.0 · 1×
babel-preset-es20156.0.0 · 1×
babel-preset-es20176.24.1 · 1×
karma2.0.2 · 1×
karma-babel-preprocessor7.0.0 · 1×
karma-coverage1.1.1 · 1×
karma-mocha1.3.0 · 1×
karma-phantomjs-launcher1.0.4 · 1×
karma-webpack3.0.0 · 1×
keep-loader0.7.1 · 1×

For agents

$ claude mcp add fly \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact