npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nivedan

v1.0.6

Published

Promise based HTTP client for the browser based on the fetch api and XMLHttpRequest

Downloads

7

Readme

nivedan

npm version

Promise based HTTP client for the browser and node.js

Features

  • Make XMLHttpRequests from the browser
  • Make http requests from node.js
  • Supports the Promise API
  • middleware request and response
  • Transform request and response data
  • Run time middleware
  • Automatic transforms for JSON data
  • Rollbar Error tracking
  • Error expend Error with details
  • React Hooks
  • Event Emitter
  • Client side support for protecting against XSRF

Browser Support

| Chrome | Firefox | Safari | Opera | Edge | IE | | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ |

Installing

Using npm:

$ npm install nivedan

Using bower:

$ bower install nivedan

Using yarn:

$ yarn add nivedan

Example

nodejs usage

const nivedan = require('nivedan');

nivedan
	.get('/url')
	.then(function (response) {
		// handle success
		console.log(response);
	})
	.catch(function (error) {
		// handle error
		console.log(error);
	});

// Get request with query parameters

nivedan
	.get('/url', {
		params: {
			key: value,
		},
	})
	.then(function (response) {
		// handle success
		console.log(response);
	})
	.catch(function (error) {
		// handle error
		console.log(error);
	});

// Modern browser request with async and await
// with async await always used the try catch for error handling

async const method = () => {
	try {
		const response = await nivedan.get('/url');
		console.log(response);
	} catch (error) {
		console.error(error);
	}
}

// handle the multiple request togather. Its similar like promise.all
nivedan
	.resolve([nivedan.get('/url'), nivedan.get('/url')])
	.then(function (response) {
		console.log(response);
	})
	.catch(function (error) {
		console.log(error);
	});

// if you want to expand the nivedan.resolve result then use the nivedan.expend

nivedan
	.resolve([nivedan.get('/url'), nivedan.get('/url')])
	.then(
		nivedan.expand(function (acct, perms) {
			// Both requests are now complete
		})
	);

Request method aliases

// you will send array or parameter

nivedan.request(config)
nivedan.get(url[, config])
nivedan.delete(url[, config])
nivedan.head(url[, config])
nivedan.options(url[, config])
nivedan.post(url[, data[, config]])
nivedan.put(url[, data[, config]])
nivedan.patch(url[, data[, config]])
NOTE

When using the alias methods url, method, and data properties don't need to be specified in config.

// Set the default common configuration for all requests

nivedan.defaultConfig({
	baseURL: 'https://something.com/apis/v2',
	headers: {
		common: { 'Content-Type': 'application/json' },
	},
	timeout: 0,
});

// config the rollbar error tracking

nivedan.defaultConfig({
	rollbarToken: '',
	rollbarConfig: {
		status: [403, 500], // track particular http error code in rollbar otherwise it will track all error code and exception
	},
});

// config the errorExpend
// without errorExpend you will get the error response regular erros

//The response for a request contains the following information.
.catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened wrong in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

nivedan.defaultConfig({
	errorExpand: true,
});
// after the config you will get

{
  clientError: true,
  errorDetails: {
    code: 403,
    success: false,
    error_message: 'This email account does not exist',
    body: []
  },
  message: 'Forbidden',
  serverError: false,
  status: 403
}

// if you want the message key from server side message so just add the
nivedan.defaultConfig({
    errorExpand: true,
    errorMessageKey: 'error_message' // key from server side which sended by the backend developer with message
});
// and result will be
{
  clientError: true,
  errorDetails: {
    code: 403,
    success: false,
    error_message: 'This email account does not exist',
    body: []
  },
  message: 'This email account does not exist',
  serverError: false,
  status: 403
}

Middleware

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

// Request middleware

nivedan.middleware.request.use(
	function (config) {
		config.headers.common['Authorization'] = 'key';
		return config;
	},
	function (error) {
		Promise.reject(error);
	}
);

// Response middleware
const successResponse = (response) => {
	// do something
	return response;
};
nivedan.middleware.response.use(
	(response) => successResponse(response),
	(error) => Promise.reject(error)
);

Additional middleware

You can run middlware before requests or responses middleware calling

When user want to do something before server requests

const checkStatus = (config, next) => {
	// todo
	next();
};
const allTaskDone = (config, next) => {
	// todo
	next();
};
nivedan.use([checkStatus, allTaskDone]);

Note: you will not modify the config in the additional middleware.

New instance

const request = nivedan.createInstance({
	baseURL: '',
});
// You can add middleware to a custom instance of nivedan.
request.middleware.request.use(function () {
	/*...*/
});

Handling Errors

nivedan.get('/user/12345').catch(function (error) {
	if (error.response) {
		// The request was made and the server responded with a status code
		// that falls out of the range of 2xx
		console.log(error.response.data);
		console.log(error.response.status);
		console.log(error.response.headers);
	} else if (error.request) {
		// The request was made but no response was received
		// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
		// http.ClientRequest in node.js
		console.log(error.request);
	} else {
		// Something happened in setting up the request that triggered an Error
		console.log('Error', error.message);
	}
	console.log(error.config);
});

Using Expend you get an object with more information about the HTTP error.

nivedan.get('/user/12345').catch(function (error) {
	console.log(error.Expend());
});

Using application/x-www-form-urlencoded format

By default, nivedan serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.

nivedan emitter

nivedan.emit('eventName', 'something');
nivedan.on('eventName', (data) => {
	console.log(data);
	// output  something
});
nivedan.get('/someurl').then(function (data) {
	nivedan.emit('eventName', data);
});
nivedan.on('eventName', (data) => {
	console.log(data);
});

nivedan global error listener

// if any error occur in the request and file so every error listen in nivedan listener
nivedan.on('error', (err) => {
	console.log(err);
});

nivedan additional config

nivedan.setConfig('s3-aws', {
	bucket: 'something',
});
nivedan.getConfig('s3-aws');
nivedan.removeConfig('s3-aws');
nivedan.getAllConfig;

License

MIT