New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

nutritionix

Package Overview
Dependencies
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

nutritionix - npm Package Compare versions

Comparing version 0.0.5 to 0.5.0

.jshintrc

99

index.js

@@ -1,67 +0,54 @@

var _ = require('underscore');
var util = require('util');
var request = require('request');
var NIX_ENV = process.env.NIX_ENV;
var DEV_MODE = NIX_ENV === 'dev';
var DEV_URL = 'http://localhost:3080';
var PRO_URL = 'https://api.nutritionix.com';
'use strict';
var formatArgs = function(args) {
return [util.format.apply(util.format, Array.prototype.slice.call(args))];
};
// initialize
require('colors');
require('lib-loader').load({
libDir: __dirname+'/lib'
});
var stringify = function (o) {
return JSON.stringify(o, null, 4);
};
// Dependencies
var _ = require('lodash');
var utils = require('lib-loader').lib.utils;
var ApiMap = require('lib-loader').lib.ApiMap;
var safeParse = function (o) {
try {
return JSON.parse(o);
} catch (e) {
// Constant Globals
var DEV_URL = process.env.DEV_URL;
var NIX_ENV = process.env.NIX_ENV;
var DEV_MODE = NIX_ENV === 'development';
var PRO_URL = 'https://api.nutritionix.com';
if (e.message === 'Unexpected token o') {
return o
}
return null
}
};
function Nutritionix(clientOpts) {
// Expose
module.exports = function (credentials, debug) {
_.defaults(clientOpts, {
appId: process.env.NIX_APP_ID,
appKey: process.env.NIX_APP_ID,
debug: false,
version: 'v2'
});
debug = debug || false;
var url = DEV_MODE ? DEV_URL : PRO_URL;
var log = new utils.DebugLogger(clientOpts.debug);
var apiMap = new ApiMap(clientOpts, url, log);
if (debug === true) {
// you will only see this if its enabled
log('Debugging is enabled');
console.debug = function(){
return console.log.apply(console.log, formatArgs(arguments));
};
return {
search: new apiMap.ApiRequest('v2.search', 'json'),
autocomplete: new apiMap.ApiRequest('v2.autocomplete', 'qs'),
'brand_search': new apiMap.ApiRequest('v2.brand_search', 'qs'),
item: new apiMap.ApiRequest('v2.item', 'qs'),
brand: new apiMap.ApiRequest('v2.brand', 'qs'),
natural: new apiMap.ApiRequest('v2.natural', 'body')
};
}
} else {
// Exposing
// =================
// new Nutritionix({
// appId: '',
// appKey: ''
// });
console.debug = function() {
return void 0
};
}
console.debug('Debugging is enabled');
// Allow url switching for DEV
var url = (DEV_MODE ? DEV_URL : PRO_URL);
var raw = require('./lib/raw')(request, credentials, stringify, safeParse);
var v1_1 = require('./lib/v1_1.js')(raw, url, '/v1_1/');
var apiLib = {
v1_1: v1_1,
url: url,
raw: raw,
safeParse: safeParse,
stringify: stringify,
formatArgs: formatArgs
};
console.debug('API Library'.blue,'\n',apiLib);
return apiLib;
};
module.exports = Nutritionix;
{
"name": "nutritionix",
"version": "0.0.5",
"version": "0.5.0",
"description": "Official Nutritionix NodeJS Client Library",

@@ -10,3 +10,3 @@ "main": "index.js",

"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "./test_runner.sh"
},

@@ -33,5 +33,7 @@ "repository": {

"dependencies": {
"async": "~0.2.10",
"bluebird": "^2.3.11",
"colors": "~0.6.2",
"async": "~0.2.10",
"underscore": "~1.6.0",
"lib-loader": "^0.4.0",
"lodash": "^2.4.1",
"request": "~2.33.0"

@@ -41,4 +43,8 @@ },

"readmeFilename": "README.md",
"_id": "nutritionix@0.0.4",
"_from": "nutritionix@"
"_id": "nutritionix@0.0.5",
"_from": "nutritionix@0.0.5",
"dist": {
"shasum": "12d8c2a87934ed095ce582324907c8906bf81553"
},
"_resolved": "https://registry.npmjs.org/nutritionix/-/nutritionix-0.0.5.tgz"
}
Official Nutritionix NodeJS Client
==================================
#### NOTE This is still in beta and the API may change until version 1.0
#### NOTE This is still in beta and the API may change until version 1.0 of this library.
#### NOTE `v1` of the API is currently not yet implemented

@@ -16,70 +17,69 @@

// Require inside your project
var nutritionix = require('nutritionix')({
var NutritionixClient = require('nutritionix');
var nutritionix = new NutritionixClient({
appId: 'YOUR_APP_ID',
appKey: 'YOUR_APP_KEY'
}, false);
// Second argument false can be changed to true
// This will tell the library to enter debugging mode
// and log additional data to the console
// debug: true, // defaults to false
});
```
### UPC Scan
### Execute an autocomplete query
```js
// GET https://api.nutritionix.com/v1_1/item?upc=52200004265
nutritionix.v1_1.item({
upc: 52200004265
}, function (err, item) {
// ...
});
// This will perform a fuzzy autocomplete query and return suggestions
nutritionix.autocomplete({ q: 'chedar che' })
.then(successHandler, errorHandler)
.catch(uncaughtExceptionHandler);
```
### Get Item by id
### Execute a natural search
```js
// GET https://api.nutritionix.com/v1_1/item?upc=52200004265
nutritionix.v1_1.item({
id: '5284ebc52504590000003f4a'
}, function (err, item) {
// ...
});
var ingredients = [
'1 tbsp sugar',
'1 red pepper'
];
// ensure you are passing a string with queries delimited by new lines.
nutritionix.natural(ingredients.join('\n'))
.then(successHandler, errorHandler)
.catch(uncaughtExceptionHandler);
```
### Get Brand By ID
### Get Item By `id` or search `resource_id`
```js
// GET https://api.nutritionix.com/v1_1/brand/51db37c3176fe9790a8991f6
nutritionix.v1_1.brand({
id: '51db37c3176fe9790a8991f6'
}, function (err, brand){
// ...
});
// this will locate an item by its (id, resource_id, or upc)
nutritionix.item({ id: 'zgcjnYV' })
.then(successHandler, errorHandler)
.catch(uncaughtExceptionHandler);
;
```
### Standard Search
### Get Brand By `id`
```js
// GET https://api.nutritionix.com/v1_1/search/mcdonalds?results=0:1
nutritionix.v1_1.search.standard({
phrase: 'mcdonalds',
results: '0:1'
}, function (err, results){
// ...
});
// this will locate a brand by its id
nutritionix.brand({ id: 'bV'})
.then(successHandler, errorHandler)
.catch(uncaughtExceptionHandler);
```
### NXQL Advanced Search
### Standard Search
```js
// POST https://api.nutritionix.com/v1_1/search -d DATA
nutritionix.v1_1.search.advanced({
fields: ['item_name','brand_name'],
query: 'mcdonalds',
offset:0,
limit:1
}, function (err, results){
// ...
});
// This will perform a search. The object passed into this function
// can contain all the perameters the API accepts in the `POST /v2/search` endpoint
nutritionix.search.standard({
q:'salad',
// use these for paging
limit: 10,
offset: 0,
// controls the basic nutrient returned in search
search_nutrient: 'calories'
}).then(successHandler, errorHandler)
.catch(uncaughtExceptionHandler);
```

@@ -90,16 +90,13 @@

```js
// GET https://api.nutritionix.com/v1_1/brand/search?query=just+salad&auto=true&type=1&min_score=1
nutritionix.v1_1.search.brand({
query:'just salad',
auto:true,
type:1,
min_score:1
}, function (err, results){
// ...
});
// This will perform a search. The object passed into this function
// can contain all the perameters the API accepts in the `GET /v2/search/brands` endpoint
nutritionix.brand_search({
q: 'just salad',
limit: 10,
offset: 0,
type: 1 // (1:restaurant, 2:cpg, 3:usda/nutritionix) defaults to undefined
}).then(successHandler, errorHandler)
.catch(uncaughtExceptionHandler);
```
#### Special thanks
Thank you to [picsoung][1] for allowing us to take over the npm package and inspiring us to create an official nodejs client.
[1]:https://www.npmjs.org/~picsoung
Take a look `tests/index.js` for an end to end usecase for these libraries.

@@ -0,63 +1,148 @@

'use strict';
require('colors');
var async = require('async');
// This contains an object that has credentials
// omitted from source control for obvious reasons
var _ = require('lodash');
var config = require('./config.testing.js');
var Nutritionix = require('../index');
var nutritionix = new Nutritionix(config);
var nutritionix = require('../index')({
appId: config.appId,
appKey: config.appKey
}, true);
var errMsgs = {
brand: 'There was a problem looking up a Brand',
item: 'There was a problem looking up an Item',
search: 'There was a problem performing a Search',
auto: 'There was an issue performing an autocomplete search',
brand_search: 'There was an issue executing a Brand Search',
natural: 'There was an issue performing a natural search',
uncaught: 'There was an uncaught exception'
};
function logJson(o) {
console.log(JSON.stringify(o,null,4));
}
var sNull = function(n) {
if (n === null) {
return 'null';
}
function RequestErrorHandler(msg) {
return function reqErrHndlr(e) {
console.error(msg.red);
return n;
};
if (_.isObject(e) && !(e instanceof Error)) {
logJson(e);
} else {
console.error(e);
}
process.exit(1);
// GET https://api.nutritionix.com/v1_1/item?upc=52200004265
nutritionix.v1_1.item({
upc: 52200004265
}, function (err, item) {
console.log('Item Callback', sNull(err).red, nutritionix.stringify(item).green);
});
};
}
// GET https://api.nutritionix.com/v1_1/brand/51db37c3176fe9790a8991f6
nutritionix.v1_1.brand({
id: '51db37c3176fe9790a8991f6'
}, function (err, brand){
console.log('Brand Callback', sNull(err).red, nutritionix.stringify(brand).green);
});
// ============================================================
// Success handlers
// ============================================================
function autoSuccess(autoResults){
var q = autoResults[0].text;
console.log('autocomplete successfull searching items using: %s'.green, q);
return nutritionix.search({
q: q
});
}
// GET https://api.nutritionix.com/v1_1/search/mcdonalds?results=0:1
nutritionix.v1_1.search.standard({
phrase: 'mcdonalds',
results: '0:1'
}, function (err, results){
console.log('Standard Search Callback', sNull(err).red, nutritionix.stringify(results).green);
});
function searchSuccess(searchResults){
var result = searchResults.results[0];
var id = result.resource_id;
// POST https://api.nutritionix.com/v1_1/search -d DATA
nutritionix.v1_1.search.advanced({
fields: ['item_name','brand_name'],
query: 'mcdonalds',
offset:0,
limit:1
}, function (err, results){
console.log('Advanced Search Callback', sNull(err).red, nutritionix.stringify(results).green);
});
var name = [
id,
result.brand_name,
result.item_name
].join(' - ');
// GET https://api.nutritionix.com/v1_1/brand/search?query=just+salad&auto=true&type=1&min_score=1&appId=c7a8b9cd&appKey=8e54cb1c548d4470701cfdddc8883a57
nutritionix.v1_1.search.brand({
query:'just salad',
auto:true,
type:1,
min_score:1
}, function (err, results){
console.log('Brand Search Callback', sNull(err).red, nutritionix.stringify(results).green);
});
console.log(('search successfull retrieving '+
'record for item: %s').green, name);
return nutritionix.item({
id: id
});
}
function itemLookUpSuccess(item){
var id = item.brand.id;
console.log('successfully located item, getting brand: %s'.green, id);
return nutritionix.brand({
id: item.brand.id
});
}
function brandLookUpSuccess(brand){
console.log('successfully located brand: %s'.green, brand.name);
return nutritionix.brand_search({
q: brand.name
});
}
function brandSearchSuccess(bsRes){
console.log('executed brand search: %d hits'.green, bsRes.total);
_.forEach(bsRes.results, function(brand){
console.log(' - %s item_count=%d website=%s'.green, brand.name,
brand.item_count,
brand.website);
});
var recipe = [
'1 tbsp sugar',
'1 red pepper'
];
return nutritionix.natural(recipe.join('\n'));
}
function naturalSearchSuccess(nRes){
console.log('executed natural search: %d hits'.green, nRes.results.length);
_.forEach(nRes.results, function(r){
var query = r.parsed_query.query;
var calories = _.find(r.nutrients, {attr_id: 208}) || {
attr_id: null,
value: null,
unit: null,
usda_tag: null
};
console.log(' - %s calories=%d'.green, query, calories.value);
});
}
// ============================================================
// Execute Tests
// ============================================================
var autocompleteQuery = {
q:'sala' // should autocomplete salad
};
console.log('attempting to autocomplete: %s'.green, autocompleteQuery.q);
// start by autocompleting a phrase
nutritionix.autocomplete(autocompleteQuery)
// perform an item search using the autocompleted phrase
.then(autoSuccess, new RequestErrorHandler(errMsgs.auto))
// grab the first item id from search and locates its entire record
.then(searchSuccess, new RequestErrorHandler(errMsgs.search))
// when an item is found attempt to locate its brand record
.then(itemLookUpSuccess, new RequestErrorHandler(errMsgs.item))
// log the brand into and end the test without failures
.then(brandLookUpSuccess, new RequestErrorHandler(errMsgs.brand))
// perform a brand search using the brands name
.then(brandSearchSuccess, new RequestErrorHandler(errMsgs.brand_search))
// perform a natural search
.then(naturalSearchSuccess, new RequestErrorHandler(errMsgs.natural))
// oops something unexpected happened
.catch(new RequestErrorHandler(errMsgs.uncaught));
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc