Skip to content
forked from ipfs/js-ipfs

Javascript API Library for interacting with the BTFS Network

License

Unknown, MIT licenses found

Licenses found

Unknown
LICENSE-APACHE
MIT
LICENSE-MIT
Notifications You must be signed in to change notification settings

TRON-US/js-btfs-api

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

BTFS http client lib logo

The JavaScript HTTP client library for BTFS implementations.



A client library for the BTFS HTTP API, implemented in JavaScript. This client library implements the interface-ipfs-core enabling applications to change between an embedded js-ipfs node and any remote BTFS node without having to change the code. In addition, this client library implements a set of utility functions.

Table of Contents

Install

This module uses node.js, and can be installed through npm:

npm install --save btfs-http-client

We support both the Current and Active LTS versions of Node.js. Please see nodejs.org for what these currently are.

Running the daemon with the right port

To interact with the API, you need to have a local daemon running. It needs to be open on the right port. 5001 is the default, and is used in the examples below, but it can be set to whatever you need.

# Show the btfs config API port to check it is correct
> btfs config Addresses.API
/ip4/127.0.0.1/tcp/5001
# Set it if it does not match the above output
> btfs config Addresses.API /ip4/127.0.0.1/tcp/5001
# Restart the daemon after changing the config

# Run the daemon
> btfs daemon

Importing the module and usage

const btfsClient = require('btfs-http-client')

// connect to ipfs daemon API server
const btfs = btfsClient('http://localhost:5001') // (the default in Node.js)

// or connect with multiaddr
const btfs = btfsClient('/ip4/127.0.0.1/tcp/5001')

// or using options
const btfs = btfsClient({ host: 'localhost', port: '5001', protocol: 'http' })

// or specifying a specific API path
const btfs = btfsClient({ host: '1.1.1.1', port: '80', apiPath: '/btfs/api/v0' })

Importing a sub-module and usage

const bitswap = require('btfs-http-client/src/bitswap')('/ip4/127.0.0.1/tcp/5001')

const list = await bitswap.wantlist(key)
// ...

In a web browser

through Browserify

Same as in Node.js, you just have to browserify the code before serving it. See the browserify repo for how to do that.

See the example in the examples folder to get a boilerplate.

through webpack

See the example in the examples folder to get an idea on how to use btfs-http-client with webpack.

from CDN

Instead of a local installation (and browserification) you may request a remote copy of BTFS API from unpkg CDN.

To always request the latest version, use the following:

<script src="https://unpkg.com/ipfs-http-client/dist/index.min.js"></script>

Note: remove the .min from the URL to get the human-readable (not minified) version.

For maximum security you may also decide to:

  • reference a specific version of BTFS API (to prevent unexpected breaking changes when a newer latest version is published)
  • generate a SRI hash of that version and use it to ensure integrity
  • set the CORS settings attribute to make anonymous requests to CDN

Example:

<script src="https://unpkg.com/btfs-http-client@9.0.0/dist/index.js"
integrity="sha384-5bXRcW9kyxxnSMbOoHzraqa7Z0PQWIao+cgeg327zit1hz5LZCEbIMx/LWKPReuB"
crossorigin="anonymous"></script>

CDN-based BTFS API provides the BtfsHttpClient constructor as a method of the global window object. Example:

const btfs = window.BtfsHttpClient({ host: 'localhost', port: 5001 })

If you omit the host and port, the client will parse window.host, and use this information. This also works, and can be useful if you want to write apps that can be run from multiple different gateways:

const btfs = window.BtfsHttpClient()

CORS

In a web browser BTFS HTTP client (either browserified or CDN-based) might encounter an error saying that the origin is not allowed. This would be a CORS ("Cross Origin Resource Sharing") failure: BTFS servers are designed to reject requests from unknown domains by default. You can whitelist the domain that you are calling from by changing your ipfs config like this:

$ btfs config --json API.HTTPHeaders.Access-Control-Allow-Origin  '["http://example.com"]'
$ btfs config --json API.HTTPHeaders.Access-Control-Allow-Methods '["PUT", "POST", "GET"]'

Custom Headers

If you wish to send custom headers with each request made by this library, for example, the Authorization header. You can use the config to do so:

const btfs = btfsClient({
  host: 'localhost',
  port: 5001,
  protocol: 'http',
  headers: {
    authorization: 'Bearer ' + TOKEN
  }
})

Global Timeouts

To set a global timeout for all requests pass a value for the timeout option:

// Timeout after 10 seconds
const btfs = btfsClient({ timeout: 10000 })
// Timeout after 2 minutes
const btfs = btfsClient({ timeout: '2m' })
// see https://www.npmjs.com/package/parse-duration for valid string values

Usage

API

btfs-http-client follows the spec defined by interface-ipfs-core, which concerns the interface to expect from BTFS implementations. This interface is a currently active endeavor. You can use it today to consult the methods available.

Renting and hosting

Files

Graph

Network

Node Management

Additional Options

All core API methods take additional options specific to the HTTP API:

  • headers - An object or Headers instance that can be used to set custom HTTP headers. Note that this option can also be configured globally via the constructor options.
  • signal - An AbortSignal that can be used to abort the request on demand.
  • timeout - A number or string specifying a timeout for the request. If the timeout is reached before data is received a TimeoutError is thrown. If a number is specified it is interpreted as milliseconds, if a string is passed, it is intepreted according to parse-duration. Note that this option can also be configured globally via the constructor options.
  • searchParams - An object or URLSearchParams instance that can be used to add additional query parameters to the query string sent with each request.

Instance Utils

  • ipfs.getEndpointConfig()

Call this on your client instance to return an object containing the host, port, protocol and api-path.

Static Types and Utils

Aside from the default export, btfs-http-client exports various types and utilities that are included in the bundle:

These can be accessed like this, for example:

const { CID } = require('btfs-http-client')
// ...or from an es-module:
import { CID } from 'btfs-http-client'
Glob source

A utility to allow files on the file system to be easily added to IPFS.

globSource(path, [options])
  • path: A path to a single file or directory to glob from
  • options: Optional options
  • options.recursive: If path is a directory, use option { recursive: true } to add the directory and all its sub-directories.
  • options.ignore: To exclude file globs from the directory, use option { ignore: ['ignore/this/folder/**', 'and/this/file'] }.
  • options.hidden: Hidden/dot files (files or folders starting with a ., for example, .git/) are not included by default. To add them, use the option { hidden: true }.

Returns an async iterable that yields { path, content } objects suitable for passing to ipfs.add.

Example
const BtfsHttpClient = require('btfs-http-client')
const { globSource } = BtfsHttpClient
const btfs = BtfsHttpClient()

for await (const file of btfs.add(globSource('./docs', { recursive: true }))) {
  console.log(file)
}
/*
{
  path: 'docs/assets/anchor.js',
  cid: CID('QmVHxRocoWgUChLEvfEyDuuD6qJ4PhdDL2dTLcpUy3dSC2'),
  size: 15347
}
{
  path: 'docs/assets/bass-addons.css',
  cid: CID('QmPiLWKd6yseMWDTgHegb8T7wVS7zWGYgyvfj7dGNt2viQ'),
  size: 232
}
...
*/
URL source

A utility to allow content from the internet to be easily added to IPFS.

urlSource(url)
  • url: A string URL or URL instance to send HTTP GET request to

Returns an async iterable that yields { path, content } objects suitable for passing to btfs.add.

Example
const BtfsHttpClient = require('btfs-http-client')
const { urlSource } = BtfsHttpClient
const btfs = BtfsHttpClient()

for await (const file of ipfs.add(urlSource('https://ipfs.io/images/ipfs-logo.svg'))) {
  console.log(file)
}
/*
{
  path: 'ipfs-logo.svg',
  cid: CID('QmTqZhR6f7jzdhLgPArDPnsbZpvvgxzCZycXK7ywkLxSyU'),
  size: 3243
}
*/

Development

Testing

We run tests by executing npm test in a terminal window. This will run both Node.js and Browser tests, both in Chrome and PhantomJS. To ensure that the module conforms with the interface-ipfs-core spec, we run the batch of tests provided by the interface module, which can be found here.

Contribute

The js-btfs-http-client is a work in progress. As such, there's a few things you can do right now to help out:

  • Check out the existing issues!
  • Perform code reviews. More eyes will help a) speed the project along b) ensure quality and c) reduce possible future bugs.
  • Add tests. There can never be enough tests. Note that interface tests exist inside interface-ipfs-core.
  • Contribute to the FAQ repository with any questions you have about BTFS or any of the relevant technology. A good example would be asking, 'What is a merkledag tree?'. If you don't know a term, odds are, someone else doesn't either. Eventually, we should have a good understanding of where we need to improve communications and teaching together to make BTFS and IPN better.

License

MIT

FOSSA Status

About

Javascript API Library for interacting with the BTFS Network

Resources

License

Unknown, MIT licenses found

Licenses found

Unknown
LICENSE-APACHE
MIT
LICENSE-MIT

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 98.1%
  • Shell 1.3%
  • Other 0.6%