Merge pull request #10 from jemartti/master

Making callbacks the last parameter + jsbeautifer
This commit is contained in:
Mr. Goferito 2015-05-23 19:50:31 +02:00
commit 12ebfcb92f
6 changed files with 418 additions and 423 deletions

View file

@ -1,36 +1,48 @@
module.exports = function(grunt) { module.exports = function (grunt) {
grunt.initConfig({ grunt.initConfig({
simplemocha: { simplemocha: {
options: { options: {
globals: ['should'], globals: ['should'],
timeout: 3000, timeout: 3000,
ignoreLeaks: false, ignoreLeaks: false,
ui: 'bdd', ui: 'bdd',
reporter: 'list' reporter: 'list'
}, },
all: { src: ['test/**/*.js'] } all: {
}, src: ['test/**/*.js']
}
},
jshint: { jsbeautifier: {
options: { files: ['Gruntfile.js', 'index.js', 'lib/**/*.js', 'test/**/*.js'],
laxbreak: true options: {
}, js: {
all: [ 'Gruntfile.js', 'index.js', 'lib/**/*.js', 'test/**/*.js'] jslintHappy: true
}, }
}
},
jsdoc: { jshint: {
all: { options: {
src: ['index.js', 'lib/**/*.js'], laxbreak: true
dest: 'doc' },
} all: ['Gruntfile.js', 'index.js', 'lib/**/*.js', 'test/**/*.js']
} },
});
grunt.loadNpmTasks('grunt-contrib-jshint'); jsdoc: {
grunt.loadNpmTasks('grunt-simple-mocha'); all: {
grunt.loadNpmTasks('grunt-jsdoc'); src: ['index.js', 'lib/**/*.js'],
dest: 'doc'
}
}
});
grunt.registerTask('test', ['simplemocha:all']); grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.registerTask('build', ['jshint', 'test']); grunt.loadNpmTasks('grunt-jsbeautifier');
grunt.registerTask('default', ['build', 'jsdoc']); grunt.loadNpmTasks('grunt-simple-mocha');
grunt.loadNpmTasks('grunt-jsdoc');
grunt.registerTask('test', ['simplemocha:all']);
grunt.registerTask('build', ['jsbeautifier', 'jshint', 'test']);
grunt.registerTask('default', ['build', 'jsdoc']);
}; };

View file

@ -16,34 +16,29 @@ var Bing = require('node-bing-api')({ accKey: "your-account-key" });
#### Web Search: #### Web Search:
```js ```js
Bing.web("Pizza", function(error, res, body){ Bing.web("Pizza", {
console.log(body);
},
{
top: 10, // Number of results (max 50) top: 10, // Number of results (max 50)
skip: 3, // Skip first 3 results skip: 3, // Skip first 3 results
}, function(error, res, body){
console.log(body);
}); });
``` ```
#### Composite Search: #### Composite Search:
```js ```js
Bing.composite("xbox", function(error, res, body){ Bing.composite("xbox", {
console.log(body);
},
{
top: 10, // Number of results (max 50) top: 10, // Number of results (max 50)
skip: 3, // Skip first 3 results skip: 3, // Skip first 3 results
sources: "web+news", //Choises are web+image+video+news+spell sources: "web+news", //Choises are web+image+video+news+spell
newssortby: "Date" //Choices are Date, Relevance newssortby: "Date" //Choices are Date, Relevance
}, function(error, res, body){
console.log(body);
}); });
``` ```
#### News Search: #### News Search:
```js ```js
Bing.news("xbox", function(error, res, body){ Bing.news("xbox", {
console.log(body);
},
{
top: 10, // Number of results (max 50) top: 10, // Number of results (max 50)
skip: 3, // Skip first 3 results skip: 3, // Skip first 3 results
newssortby: "Date" //Choices are: Date, Relevance newssortby: "Date" //Choices are: Date, Relevance
@ -56,40 +51,40 @@ Bing.news("xbox", function(error, res, body){
// rt_US // rt_US
// rt_World // rt_World
// rt_ScienceAndTechnology // rt_ScienceAndTechnology
}, function(error, res, body){
console.log(body);
}); });
``` ```
#### Video Search: #### Video Search:
```js ```js
Bing.video("monkey vs frog", function(error, res, body){ Bing.video("monkey vs frog", {
console.log(body);
},
{
top: 10, // Number of results (max 50) top: 10, // Number of results (max 50)
skip: 3, // Skip first 3 result skip: 3, // Skip first 3 result
videofilters: { videofilters: {
duration: 'short', duration: 'short',
resolution: 'high' resolution: 'high'
} }
}, function(error, res, body){
console.log(body);
}); });
``` ```
#### Images Search: #### Images Search:
```js ```js
Bing.images("Ninja Turtles", function(error, res, body){ Bing.images("Ninja Turtles", {skip: 50}, function(error, res, body){
console.log(body); console.log(body);
}, {skip: 50}); });
``` ```
Adding filter(s) for the Image Search Adding filter(s) for the Image Search
```js ```js
Bing.images("Ninja Turtles", function(error, res, body){ Bing.images("Ninja Turtles", {
console.log(body);
},
{
imagefilters: { imagefilters: {
size: 'small', size: 'small',
color: 'monochrome' color: 'monochrome'
} }
}, function(error, res, body){
console.log(body);
}); });
``` ```
Accepted filter values: Accepted filter values:
@ -105,18 +100,18 @@ Accepted filter values:
#### Specify Market #### Specify Market
Getting spanish results: Getting spanish results:
```js ```js
Bing.images("Ninja Turtles", function(error, res, body){ Bing.images("Ninja Turtles", {top: 5, market: 'es-ES'}, function(error, res, body){
console.log(body); console.log(body);
}, {top: 5, market: 'es-ES'}); });
``` ```
[List of Bing Markets](https://msdn.microsoft.com/en-us/library/dd251064.aspx) [List of Bing Markets](https://msdn.microsoft.com/en-us/library/dd251064.aspx)
#### Adult Filter #### Adult Filter
```js ```js
Bing.images('Kim Kardashian', function(error, res, body){ Bing.images('Kim Kardashian', {market: 'en-US', adult: 'Strict'}, function(error, res, body){
console.log(body.d.results); console.log(body.d.results);
}, { market: 'en-US', adult: 'Strict'}); });
``` ```
Accepted values: "Off", "Moderate", "Strict". Accepted values: "Off", "Moderate", "Strict".
@ -126,4 +121,3 @@ or videos, but may include sexually explicit text.*
## License ## License
MIT MIT

View file

@ -1,240 +1,226 @@
/*********************************************************
/********************************************************* * Simple Node.js module for using the Bing Search API *
* Simple Node.js module for using the Bing Search API * *********************************************************/
*********************************************************/
// Require dependencies
// Require dependencies var request = require('request'),
var request = require('request'), url = require('url'),
url = require('url'), _ = require('underscore'),
_ = require('underscore'), qs = require('querystring');
qs = require('querystring');
/**
/** * @param {Object} options Options to all Bing calls, allows overriding of
* @param {Object} options Options to all Bing calls, allows overriding of * rootUri, accKey (Bing API key), userAgent, reqTimeout
* rootUri, accKey (Bing API key), userAgent, reqTimeout * @returns {Bing}
* @returns {Bing} * @constructor
* @constructor */
*/ var Bing = function (options) {
var Bing = function( options ) {
if (!(this instanceof Bing)) return new Bing(options);
if( !(this instanceof Bing) ) return new Bing( options );
var defaults = {
var defaults = {
//Bing Search API URI
//Bing Search API URI rootUri: "https://api.datamarket.azure.com/Bing/Search/v1/",
rootUri: "https://api.datamarket.azure.com/Bing/Search/v1/",
//Account Key
//Account Key accKey: null,
accKey: null,
//Bing UserAgent
//Bing UserAgent userAgent: 'Bing Search Client for Node.js',
userAgent: 'Bing Search Client for Node.js',
//Request Timeout
//Request Timeout reqTimeout: 5000,
reqTimeout: 5000,
// Number of results (limited to 50 by API)
// Number of results (limited to 50 by API) top: 50,
top: 50,
// Number of skipped results (pagination)
// Number of skipped results (pagination) skip: 0
skip: 0
};
};
//merge options passed in with defaults
//merge options passed in with defaults this.options = _.extend(defaults, options);
this.options = _.extend(defaults, options);
this.searchVertical = function (query, vertical, options, callback) {
this.searchVertical = function(query, vertical, callback, options) { if (typeof options === 'function') {
callback = options;
if(typeof callback != 'function') { }
throw "Error: Callback function required!"; if (typeof callback != 'function') {
} throw "Error: Callback function required!";
}
// Create a copy of the options, to avoid permanent overwrites
var opts = JSON.parse(JSON.stringify(this.options)); // Create a copy of the options, to avoid permanent overwrites
var opts = JSON.parse(JSON.stringify(this.options));
_.extend(opts, options);
if (typeof options === 'object') {
var reqUri = opts.rootUri _.extend(opts, options);
+ vertical }
+ "?$format=json&"
+ qs.stringify({ "Query": "'" + query + "'" }) var reqUri = opts.rootUri + vertical + "?$format=json&" + qs.stringify({
+ "&$top=" + opts.top "Query": "'" + query + "'"
+ "&$skip=" + opts.skip }) + "&$top=" + opts.top + "&$skip=" + opts.skip + (opts.sources ? "&Sources=%27" + opts.sources + "%27" : '') + (opts.newssortby ? "&NewsSortBy=%27" + opts.newssortby + "%27" : '') + (opts.newscategory ? "&NewsCategory=%27" + opts.newscategory + "%27" : '') + (opts.newslocationoverride ? "&NewsLocationOverride=%27" + opts.newslocationoverride + "%27" : '') + (opts.market ? "&Market=%27" + opts.market + "%27" : '') + (opts.adult ? "&Adult=%27" + opts.adult + "%27" : '') + (opts.imagefilters ? '&' + qs.stringify({
+ (opts.sources ? "&Sources=%27" + opts.sources + "%27" : '') "ImageFilters": "'" + opts.imagefilters + "'"
+ (opts.newssortby ? "&NewsSortBy=%27" + opts.newssortby + "%27" : '') }) : '') + (opts.videofilters ? '&' + qs.stringify({
+ (opts.newscategory ? "&NewsCategory=%27" + opts.newscategory + "%27" : '') "VideoFilters": "'" + opts.videofilters + "'"
+ (opts.newslocationoverride ? "&NewsLocationOverride=%27" + opts.newslocationoverride + "%27" : '') }) : '');
+ (opts.market ? "&Market=%27" + opts.market + "%27" : '')
+ (opts.adult ? "&Adult=%27" + opts.adult + "%27" : '') request({
+ (opts.imagefilters uri: reqUri,
? '&' + qs.stringify({ "ImageFilters": "'" + opts.imagefilters + "'" }) method: opts.method || "GET",
: '') headers: {
+ (opts.videofilters "User-Agent": opts.userAgent
? '&' + qs.stringify({ "VideoFilters": "'" + opts.videofilters + "'" }) },
: ''); auth: {
user: opts.accKey,
request({ pass: opts.accKey
uri: reqUri, },
method: opts.method || "GET", timeout: opts.reqTimeout
headers: {
"User-Agent": opts.userAgent }, function (err, res, body) {
},
auth: { if (res && res.statusCode !== 200) {
user: opts.accKey, err = new Error(body);
pass: opts.accKey } else {
},
timeout: opts.reqTimeout // Parse body, if body
body = typeof body === 'string' ? JSON.parse(body) : body;
}, function(err, res, body){ }
if(res && res.statusCode !== 200){ callback(err, res, body);
err = new Error(body); });
}else{ };
// Parse body, if body };
body = typeof body === 'string'
? JSON.parse(body)
: body; /**
} * @callback requestCallback
* @param {String} error Error evaluates to true when an error has occurred.
callback(err, res, body); * @param {Object} response Response object from the Bing call.
}); * @param {Object} body JSON of the response.
}; */
};
/**
* Performs a Bing search in the Web vertical.
/** *
* @callback requestCallback * @param {String} query Query term to search for.
* @param {String} error Error evaluates to true when an error has occurred. *
* @param {Object} response Response object from the Bing call. * @param {Object} options Options to command, allows overriding
* @param {Object} body JSON of the response. * of rootUri, accKey (Bing API key),
*/ * userAgent, reqTimeout, top, skip
*
* @param {requestCallback} callback Callback called with (potentially
/** * json-parsed) response.
* Performs a Bing search in the Web vertical. *
* * @function
* @param {String} query Query term to search for. */
* Bing.prototype.web = function (query, options, callback) {
* @param {requestCallback} callback Callback called with (potentially this.searchVertical(query, "Web", options, callback);
* json-parsed) response. };
*
* @param {Object} options Options to command, allows overriding // Alias Bing.search to Bing.web
* of rootUri, accKey (Bing API key), // Note: Keep this for compatibility with older versions
* userAgent, reqTimeout, top, skip Bing.prototype.search = Bing.prototype.web;
* @function
*/
Bing.prototype.web = function(query, callback, options) { /**
this.searchVertical(query, "Web", callback, options); * Performs a Bing search in the Composite vertical.
}; *
* @param {String} query Query term to search for.
// Alias Bing.search to Bing.web *
// Note: Keep this for compatibility with older versions * @param {Object} options Options to command, allows overriding
Bing.prototype.search = Bing.prototype.web; * of rootUri, accKey (Bing API key),
* userAgent, reqTimeout, top, skip,
*
/** * @param {requestCallback} callback Callback called with (potentially
* Performs a Bing search in the Composite vertical. * json-parsed) response.
* * @function
* @param {String} query Query term to search for. */
* Bing.prototype.composite = function (query, options, callback) {
* @param {requestCallback} callback Callback called with (potentially this.searchVertical(query, "Composite", options, callback);
* json-parsed) response. };
*
* @param {Object} options Options to command, allows overriding /**
* of rootUri, accKey (Bing API key), * Performs a Bing search in the News vertical.
* userAgent, reqTimeout, top, skip, *
* @function * @param {String} query Query term to search for.
*/ *
Bing.prototype.composite = function(query, callback, options) { * @param {Object} options Options to command, allows overriding
this.searchVertical(query, "Composite", callback, options); * of rootUri, accKey (Bing API key),
}; * userAgent, reqTimeout, top, skip,
*
/** * @param {requestCallback} callback Callback called with (potentially
* Performs a Bing search in the News vertical. * json-parsed) response.
* * @function
* @param {String} query Query term to search for. */
* Bing.prototype.news = function (query, options, callback) {
* @param {requestCallback} callback Callback called with (potentially this.searchVertical(query, "News", options, callback);
* json-parsed) response. };
*
* @param {Object} options Options to command, allows overriding /**
* of rootUri, accKey (Bing API key), * Performs a Bing search in the Video vertical.
* userAgent, reqTimeout, top, skip, *
* @function * @param {String} query Query term to search for.
*/ *
Bing.prototype.news = function(query, callback, options) { * @param {Object} options Options to command, allows overriding
this.searchVertical(query, "News", callback, options); * of rootUri, accKey (Bing API key),
}; * userAgent, reqTimeout, top, skip,
*
/** * @param {requestCallback} callback Callback called with (potentially
* Performs a Bing search in the Video vertical. * json-parsed) response.
* * @function
* @param {String} query Query term to search for. */
* Bing.prototype.video = function (query, options, callback) {
* @param {requestCallback} callback Callback called with (potentially if (options && typeof options === 'object' && options.videofilters && typeof options.videofilters === 'object') {
* json-parsed) response. var filterQuery = '';
* var filters = Object.keys(options.videofilters);
* @param {Object} options Options to command, allows overriding filters.map(function (key, i) {
* of rootUri, accKey (Bing API key), filterQuery += capitalizeFirstLetter(key) + ':';
* userAgent, reqTimeout, top, skip, filterQuery += capitalizeFirstLetter(options.videofilters[key]);
* @function if (i < filters.length - 1)
*/ filterQuery += '+';
Bing.prototype.video = function(query, callback, options) { });
if (options options.videofilters = filterQuery;
&& options.videofilters }
&& typeof options.videofilters === 'object') { this.searchVertical(query, "Video", options, callback);
var filterQuery = ''; };
var filters = Object.keys(options.videofilters);
filters.map(function(key, i) {
filterQuery += capitalizeFirstLetter(key) + ':';
filterQuery += capitalizeFirstLetter(options.videofilters[key]); /**
if (i < filters.length - 1) * Performs a Bing search in the Images vertical.
filterQuery += '+'; *
}); * @param {String} query Query term to search for.
options.videofilters = filterQuery; *
} * @param {Object} options Options to command, allows overriding of
this.searchVertical(query, "Video", callback, options); * rootUri, accKey (Bing API key),
}; * userAgent, reqTimeout, top, skip,
* imagefilters
*
* @param {requestCallback} callback Callback called with (potentially
/** * json-parsed) response.
* Performs a Bing search in the Images vertical. * @function
* */
* @param {String} query Query term to search for. Bing.prototype.images = function (query, options, callback) {
* if (options && typeof options === 'object' && options.imagefilters && typeof options.imagefilters === 'object') {
* @param {requestCallback} callback Callback called with (potentially var filterQuery = '';
* json-parsed) response. var filters = Object.keys(options.imagefilters);
* filters.map(function (key, i) {
* @param {Object} options Options to command, allows overriding of filterQuery += capitalizeFirstLetter(key) + ':';
* rootUri, accKey (Bing API key), filterQuery += capitalizeFirstLetter(options.imagefilters[key]);
* userAgent, reqTimeout, top, skip, if (i < filters.length - 1)
* imagefilters filterQuery += '+';
* @function });
*/ options.imagefilters = filterQuery;
Bing.prototype.images = function(query, callback, options) { }
if (options this.searchVertical(query, "Image", options, callback);
&& options.imagefilters };
&& typeof options.imagefilters === 'object') {
var filterQuery = ''; function capitalizeFirstLetter(s) {
var filters = Object.keys(options.imagefilters); return s.charAt(0).toUpperCase() + s.slice(1);
filters.map(function(key, i) { }
filterQuery += capitalizeFirstLetter(key) + ':';
filterQuery += capitalizeFirstLetter(options.imagefilters[key]); module.exports = Bing;
if (i < filters.length - 1)
filterQuery += '+';
});
options.imagefilters = filterQuery;
}
this.searchVertical(query, "Image", callback, options);
};
function capitalizeFirstLetter(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}
module.exports = Bing;

View file

@ -20,6 +20,7 @@
"express": "^4.9.5", "express": "^4.9.5",
"grunt": "^0.4.5", "grunt": "^0.4.5",
"grunt-contrib-jshint": "^0.10.0", "grunt-contrib-jshint": "^0.10.0",
"grunt-jsbeautifier": "~0.2.10",
"grunt-jsdoc": "^0.5.7", "grunt-jsdoc": "^0.5.7",
"grunt-simple-mocha": "^0.4.0", "grunt-simple-mocha": "^0.4.0",
"mocha": "^1.21.4", "mocha": "^1.21.4",

View file

@ -1,31 +1,28 @@
var validWebResponse = { var validWebResponse = {
"d": { "d": {
"results": [ "results": [{
{ "__metadata": {
"__metadata": { "uri": "https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Query='xbox'&$skip=0&$top=1",
"uri": "https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Query='xbox'&$skip=0&$top=1", "type": "WebResult"
"type": "WebResult" },
}, "ID": "26888c2a-d245-47dc-87de-dc3551249de7",
"ID": "26888c2a-d245-47dc-87de-dc3551249de7", "Title": "Xbox | Games and Entertainment on All Your Devices",
"Title": "Xbox | Games and Entertainment on All Your Devices", "Description": "Experience the new generation of games and entertainment with Xbox. Play Xbox games and stream video on all your devices.",
"Description": "Experience the new generation of games and entertainment with Xbox. Play Xbox games and stream video on all your devices.", "DisplayUrl": "www.xbox.com",
"DisplayUrl": "www.xbox.com", "Url": "http://www.xbox.com/"
"Url": "http://www.xbox.com/" }, {
}, "__metadata": {
{ "uri": "https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Query='xbox'&$skip=1&$top=1",
"__metadata": { "type": "WebResult"
"uri": "https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Query='xbox'&$skip=1&$top=1", },
"type": "WebResult" "ID": "ff23e110-31c2-44f9-be21-f213bcd4c654",
}, "Title": "Amazon.com: Xbox - More Systems: Video Games: Games ...",
"ID": "ff23e110-31c2-44f9-be21-f213bcd4c654", "Description": "Online shopping for Video Games from a great selection of Games, Hardware, Computer And Console Video Game Products & more at everyday low prices.",
"Title": "Amazon.com: Xbox - More Systems: Video Games: Games ...", "DisplayUrl": "www.amazon.com/Xbox-Games/b?ie=UTF8&node=537504",
"Description": "Online shopping for Video Games from a great selection of Games, Hardware, Computer And Console Video Game Products & more at everyday low prices.", "Url": "http://www.amazon.com/Xbox-Games/b?ie=UTF8&node=537504"
"DisplayUrl": "www.amazon.com/Xbox-Games/b?ie=UTF8&node=537504", }],
"Url": "http://www.amazon.com/Xbox-Games/b?ie=UTF8&node=537504" "__next": "https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Query='xbox'&$skip=2"
} }
],
"__next": "https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Query='xbox'&$skip=2"
}
}; };
var should = require('should'), var should = require('should'),
@ -34,7 +31,7 @@ var should = require('should'),
request = require('request'), request = require('request'),
bing = require('../lib/bing'); bing = require('../lib/bing');
describe('Bing', function() { describe('Bing', function () {
var server; var server;
var app; var app;
var port = 4321; var port = 4321;
@ -43,13 +40,14 @@ describe('Bing', function() {
app = express(); app = express();
server = http.createServer(app); server = http.createServer(app);
server.listen.apply(server, [port, server.listen.apply(server, [port,
function(err, result) { function (err, result) {
if (err) { if (err) {
done(err); done(err);
} else { } else {
done(); done();
} }
}]); }
]);
}); });
after(function (done) { after(function (done) {
@ -59,11 +57,14 @@ describe('Bing', function() {
done(); done();
}); });
it('should cope with valid responses', function(done) { it('should cope with valid responses', function (done) {
app.get('/hello/Web', function (req, res) { app.get('/hello/Web', function (req, res) {
res.status(200).send(JSON.stringify(validWebResponse)); res.status(200).send(JSON.stringify(validWebResponse));
}); });
var bingClient = bing({ rootUri: 'http://localhost:'+port+'/hello/', accKey: '123' }); var bingClient = bing({
rootUri: 'http://localhost:' + port + '/hello/',
accKey: '123'
});
bingClient.search('xbox', function (error, response, body) { bingClient.search('xbox', function (error, response, body) {
response.statusCode.should.eql(200); response.statusCode.should.eql(200);
body.should.eql(validWebResponse); body.should.eql(validWebResponse);
@ -71,13 +72,18 @@ describe('Bing', function() {
}); });
}); });
it('should cope with errors', function(done) { it('should cope with errors', function (done) {
// No actual data on what the failure looks like. // No actual data on what the failure looks like.
var failure = { message: 'Failed request' }; var failure = {
message: 'Failed request'
};
app.get('/hello/Image', function (req, res) { app.get('/hello/Image', function (req, res) {
res.status(500).send(failure); res.status(500).send(failure);
});
var bingClient = bing({
rootUri: 'http://localhost:' + port + '/hello/',
accKey: '123'
}); });
var bingClient = bing({ rootUri: 'http://localhost:'+port+'/hello/', accKey: '123' });
bingClient.images('xbox', function (error, response, body) { bingClient.images('xbox', function (error, response, body) {
response.statusCode.should.eql(500); response.statusCode.should.eql(500);
body.should.eql(JSON.stringify(failure)); body.should.eql(JSON.stringify(failure));

View file

@ -1,137 +1,133 @@
// Try to get an access key to run all this test. // Try to get an access key to run all this test.
// If the file doesn't exist or it doesn't contain an access key, it // If the file doesn't exist or it doesn't contain an access key, it
// should still run the basic tests; thus throwing an exception must // should still run the basic tests; thus throwing an exception must
// be avoided. // be avoided.
try{ try {
var accKey = require('./secrets').accKey; var accKey = require('./secrets').accKey;
} catch (e) {
console.log(e);
} }
catch(e){ console.log(e) }
if(!accKey){ if (!accKey) {
return console.error("Need to include an access key in your secrets.js"); return console.error("Need to include an access key in your secrets.js");
} }
var Bing = require('../')({ accKey: accKey}) var Bing = require('../')({
, should = require('should') accKey: accKey
});
var should = require('should');
describe("Bing Search", function(){ describe("Bing Search", function () {
this.timeout(1000 * 10); this.timeout(1000 * 10);
it('works without options', function(done){ it('works without options', function (done) {
Bing.search('nigger vs chink', function(err, res, body){ Bing.search('monkey vs frog', function (err, res, body) {
should.not.exist(err); should.not.exist(err);
should.exist(res); should.exist(res);
should.exist(body); should.exist(body);
body.d.results.should.have.length(50); body.d.results.should.have.length(50);
//TODO check it contains the right fields //TODO check it contains the right fields
done(); done();
});
}); });
});
it('finds only 5 results', function(done){ it('finds only 5 results', function (done) {
Bing.search('nigger vs chink', function(err, res, body){ Bing.search('monkey vs frog', {
top: 5,
market: 'en-US',
adult: 'Strict'
}, function (err, res, body) {
should.not.exist(err);
should.exist(res);
should.exist(body);
should.not.exist(err); body.d.results.should.have.length(5);
should.exist(res);
should.exist(body);
body.d.results.should.have.length(5); done();
});
done();
},
{
top: 5,
market: 'en-US',
adult: 'Strict'
}); });
});
}); });
describe("Bing Images", function(){ describe("Bing Images", function () {
this.timeout(1000 * 10); this.timeout(1000 * 10);
it('finds images with specific options', function(done){ it('finds images with specific options', function (done) {
Bing.images('pizza', Bing.images('pizza', {
function(err, res, body){ top: 3,
adult: 'Off',
imagefilters: {
size: 'small',
color: 'monochrome'
}
}, function (err, res, body) {
should.not.exist(err);
should.exist(res);
should.exist(body);
should.not.exist(err); body.d.results.should.have.length(3);
should.exist(res);
should.exist(body);
body.d.results.should.have.length(3); done();
});
done();
},
{
top: 3,
adult: 'Off',
imagefilters: { size: 'small', color: 'monochrome' }
}); });
});
}); });
describe("Bing News", function(){ describe("Bing News", function () {
this.timeout(1000 * 10); this.timeout(1000 * 10);
it('finds news with specific options', function(done){ it('finds news with specific options', function (done) {
Bing.news('ps4', function(err, res, body){ Bing.news('ps4', {
//TODO try unaccepted options like imagefilters top: 10,
skip: 1,
newsortby: 'Date'
}, function (err, res, body) {
//TODO try unaccepted options like imagefilters
should.not.exist(err); should.not.exist(err);
should.exist(res); should.exist(res);
should.exist(body); should.exist(body);
body.d.results.should.have.length(10); body.d.results.should.have.length(10);
done(); done();
}, });
{
top: 10,
skip: 1,
newsortby: 'Date'
}); });
});
}); });
describe("Bing Video", function(){ describe("Bing Video", function () {
this.timeout(1000 * 10); this.timeout(1000 * 10);
it('finds videos with specific options', function(done){ it('finds videos with specific options', function (done) {
Bing.video('monkey vs frog', function(err, res, body){ Bing.video('monkey vs frog', {
top: 10
}, function (err, res, body) {
should.not.exist(err);
should.exist(res);
should.exist(body);
should.not.exist(err); body.d.results.should.have.length(10);
should.exist(res);
should.exist(body);
body.d.results.should.have.length(10); //TODO try here unaccepted options like imagefilters
//TODO try here unaccepted options like imagefilters done();
});
done();
},
{
top: 10
}); });
});
});
});