Merge pull request #25 from franciscofsales/master

Upgrading to API V5
This commit is contained in:
Mr. Goferito 2016-10-31 19:15:00 +01:00 committed by GitHub
commit 682ca178b6
4 changed files with 70 additions and 131 deletions

View file

@ -18,28 +18,25 @@ Require the library and initialialize it with your account key:
var Bing = require('node-bing-api')({ accKey: "your-account-key" }); var Bing = require('node-bing-api')({ accKey: "your-account-key" });
``` ```
#### Web Search: #### Web Search (same as Composite):
```js ```js
Bing.web("Pizza", { Bing.web("Pizza", {
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
options: ['DisableLocationDetection', 'EnableHighlighting']
}, function(error, res, body){ }, function(error, res, body){
// body has more useful information, but for this example we are just // body has more useful information, but for this example we are just
// printing the first two results // printing the first two results
console.log(body.d.results[0]); console.log(body.webPages.value[0]);
console.log(body.d.results[1]); console.log(body.webPages.value[1]);
}); });
``` ```
#### Composite Search: #### Composite Search (same as Web):
```js ```js
Bing.composite("xbox", { Bing.composite("xbox", {
top: 10, // Number of results (max 15 for news, max 50 if other) top: 10, // Number of results (max 15 for news, max 50 if other)
skip: 3, // Skip first 3 results skip: 3 // Skip first 3 results
sources: "web+news", //Choises are web+image+video+news+spell
newsSortBy: "Date" //Choices are Date, Relevance
}, function(error, res, body){ }, function(error, res, body){
console.log(body); console.log(body);
}); });
@ -49,18 +46,7 @@ Bing.composite("xbox", {
```js ```js
Bing.news("xbox", { Bing.news("xbox", {
top: 10, // Number of results (max 15) top: 10, // Number of results (max 15)
skip: 3, // Skip first 3 results skip: 3 // Skip first 3 results
newsSortBy: "Date", //Choices are: Date, Relevance
newsCategory: "rt_Business" // Choices are:
// rt_Business
// rt_Entertainment
// rt_Health
// rt_Politics
// rt_Sports
// rt_US
// rt_World
// rt_ScienceAndTechnology
newsLocationOverride: "US.WA" // Only for en-US market
}, function(error, res, body){ }, function(error, res, body){
console.log(body); console.log(body);
}); });
@ -70,14 +56,7 @@ Bing.news("xbox", {
```js ```js
Bing.video("monkey vs frog", { Bing.video("monkey vs frog", {
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: {
duration: 'short',
resolution: 'high'
},
videoSortBy: 'Date' // Choices are:
// Date
// Relevance
}, function(error, res, body){ }, function(error, res, body){
console.log(body); console.log(body);
}); });
@ -92,27 +71,16 @@ Bing.images("Ninja Turtles", {skip: 50}, function(error, res, body){
Adding filter(s) for the Image Search Adding filter(s) for the Image Search
```js ```js
Bing.images("Ninja Turtles", { Bing.images("Ninja Turtles", {
imageFilters: { top: 5 // Number of results (max 50)
size: 'small',
color: 'monochrome'
}
}, function(error, res, body){ }, function(error, res, body){
console.log(body); console.log(body);
}); });
``` ```
Accepted filter values:
* Size:\<Small | Medium | Large\>
* Size:Height:\<*Height*\>
* Size:Width:\<*Width*\>
* Aspect:\<Square | Wide | Tall\>
* Color:\<Color | Monochrome\>
* Style:\<Photo | Graphics\>
* Face:\<Face | Portrait | Other\>
#### Related Search: #### Related Search (same as Web):
```js ```js
Bing.relatedSearch('berlin', {market: 'en-US'}, function (err, res, body) { Bing.relatedSearch('berlin', {market: 'en-US'}, function (err, res, body) {
var suggestions = body.d.results.map(function(r){ return r.Title; }); var suggestions = body.relatedSearches.value.map(function(r){ return r.Title; });
console.log(suggestions.join('\n')); console.log(suggestions.join('\n'));
}); });
``` ```
@ -120,10 +88,17 @@ Bing.relatedSearch('berlin', {market: 'en-US'}, function (err, res, body) {
#### Spelling Suggestions: #### Spelling Suggestions:
```js ```js
Bing.spelling('awsome spell', function (err, res, body) { Bing.spelling('awsome spell', function (err, res, body) {
console.log(body.d.results[0]); //awesome spell console.log(body.flaggedTokens.suggestions[0].suggestion); //awesome spell
}); });
``` ```
Requires specific Account key
Available Options:
* mode:\<Proof | Spell\>
* preContextText:\<*String*\>
* postContextText:\<*String*\>
#### Specify Market #### Specify Market
Getting spanish results: Getting spanish results:
```js ```js
@ -155,9 +130,9 @@ or videos, but may include sexually explicit text.*
To use this library with a web only subscription, you can require and initialize it with an alternate root url: To use this library with a web only subscription, you can require and initialize it with an alternate root url:
```js ```js
var Bing = require('node-bing-api') var Bing = require('node-bing-api')
({ ({
accKey: "your-account-key", accKey: "your-account-key",
rootUri: "https://api.datamarket.azure.com/Bing/SearchWeb/v1/" rootUri: "https://api.datamarket.azure.com/Bing/SearchWeb/v1/"
}); });
``` ```
@ -170,4 +145,3 @@ Then just `mocha`.
## License ## License
MIT MIT

View file

@ -21,7 +21,7 @@ var Bing = function (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.cognitive.microsoft.com/bing/v5.0/",
//Account Key //Account Key
accKey: null, accKey: null,
@ -59,51 +59,30 @@ var Bing = function (options) {
_.extend(opts, options); _.extend(opts, options);
} }
// Use camelCased options
// Note: this translation is needed for compatibility with older versions.
// At some point it could be deprecated and removed in a major version
opts.newsSortBy = opts.newsSortBy || opts.newssortby || null;
opts.newsCategory = opts.newsCategory || opts.newscategory || null;
opts.newsLocationOverride = opts.newsLocationOverride
|| opts.newslocationoverride
|| null;
opts.imageFilters = opts.imageFilters || opts.imagefilters || null;
opts.videoSortBy = opts.videoSortBy || opts.videosortby || null; opts.videoSortBy = opts.videoSortBy || opts.videosortby || null;
opts.videoFilters = opts.videoFilters || opts.videofilters || null; opts.videoFilters = opts.videoFilters || opts.videofilters || null;
var reqUri = opts.rootUri var reqUri = opts.rootUri
+ vertical + vertical
+ "?$format=json&" + qs.stringify({ "Query": "'" + query + "'" }) + (vertical == 'spellcheck' ? "?text=" : "?q=") + query
+ "&$top=" + opts.top + (opts.top ? "&count=" + opts.top : "")
+ "&$skip=" + opts.skip + (opts.offset ? "&offset=" + opts.skip : "")
+ "&Options=%27" + (opts.options || []).join('%2B') + "%27" + (opts.preContextText ? "&preContextText=" + opts.preContextText : "")
+ (opts.mode ? "&mode=" + opts.mode : "")
+ (opts.postContextText ? "&postContextText=" + opts.postContextText : "")
// + "&Options='" + (opts.options || []).join('%2B') + "'"
+ (opts.sources + (opts.sources
? "&Sources=%27" + encodeURIComponent(opts.sources) + "%27" ? "&Sources='" + encodeURIComponent(opts.sources) + "'"
: '') : '')
+ (opts.newsSortBy ? "&NewsSortBy=%27" + opts.newsSortBy + "%27" : '') + (opts.market ? "&mkt='" + opts.market + "'" : '')
+ (opts.newsCategory ? "&NewsCategory=%27" + opts.newsCategory + "%27" : '') + (opts.adult ? "&safesearch=" + opts.adult : '')
+ (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({ "ImageFilters": "'" + opts.imageFilters + "'" })
: '')
+ (opts.videoSortBy ? "&VideoSortBy=%27" + opts.videoSortBy + "%27" : '')
+ (opts.videoFilters
? '&' + qs.stringify({ "VideoFilters": "'" + opts.videoFilters + "'" })
: '');
request({ request({
uri: reqUri, uri: reqUri,
method: opts.method || "GET", method: opts.method || "GET",
headers: { headers: {
"User-Agent": opts.userAgent "User-Agent": opts.userAgent,
}, "Ocp-Apim-Subscription-Key": opts.accKey
auth: {
user: opts.accKey,
pass: opts.accKey
}, },
timeout: opts.reqTimeout timeout: opts.reqTimeout
@ -147,7 +126,7 @@ var Bing = function (options) {
* @function * @function
*/ */
Bing.prototype.web = function (query, options, callback) { Bing.prototype.web = function (query, options, callback) {
this.searchVertical(query, "Web", options, callback); this.searchVertical(query, "search", options, callback);
}; };
// Alias Bing.search to Bing.web // Alias Bing.search to Bing.web
@ -169,7 +148,7 @@ Bing.prototype.search = Bing.prototype.web;
* @function * @function
*/ */
Bing.prototype.composite = function (query, options, callback) { Bing.prototype.composite = function (query, options, callback) {
this.searchVertical(query, "Composite", options, callback); this.searchVertical(query, "search", options, callback);
}; };
/** /**
@ -186,7 +165,7 @@ Bing.prototype.composite = function (query, options, callback) {
* @function * @function
*/ */
Bing.prototype.news = function (query, options, callback) { Bing.prototype.news = function (query, options, callback) {
this.searchVertical(query, "News", options, callback); this.searchVertical(query, "news/search", options, callback);
}; };
/** /**
@ -220,7 +199,7 @@ Bing.prototype.video = function (query, options, callback) {
options.videoFilters = filterQuery; options.videoFilters = filterQuery;
} }
} }
this.searchVertical(query, "Video", options, callback); this.searchVertical(query, "videos/search", options, callback);
}; };
@ -257,7 +236,7 @@ Bing.prototype.images = function (query, options, callback) {
options.imageFilters = filterQuery; options.imageFilters = filterQuery;
} }
} }
this.searchVertical(query, "Image", options, callback); this.searchVertical(query, "images/search", options, callback);
}; };
@ -275,7 +254,7 @@ Bing.prototype.images = function (query, options, callback) {
* @function * @function
*/ */
Bing.prototype.relatedSearch = function (query, options, callback) { Bing.prototype.relatedSearch = function (query, options, callback) {
this.searchVertical(query, "RelatedSearch", options, callback); this.searchVertical(query, "search", options, callback);
}; };
@ -293,7 +272,7 @@ Bing.prototype.relatedSearch = function (query, options, callback) {
* @function * @function
*/ */
Bing.prototype.spelling = function (query, options, callback) { Bing.prototype.spelling = function (query, options, callback) {
this.searchVertical(query, "SpellingSuggestions", options, callback); this.searchVertical(query, "spellcheck", options, callback);
}; };
@ -311,4 +290,3 @@ function capitalise(s) {
module.exports = Bing; module.exports = Bing;

View file

@ -59,7 +59,7 @@ describe('Bing', function () {
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/search', function (req, res) {
res.status(200).send(JSON.stringify(validWebResponse)); res.status(200).send(JSON.stringify(validWebResponse));
}); });
@ -82,10 +82,10 @@ describe('Bing', function () {
message: 'Failed request' message: 'Failed request'
}; };
app.get('/hello/Image', function (req, res) { app.get('/hello/images/search', function (req, res) {
res.status(500).send(failure); res.status(500).send(failure);
}); });
var bingClient = bing({ var bingClient = bing({
rootUri: 'http://localhost:' + port + '/hello/', rootUri: 'http://localhost:' + port + '/hello/',
accKey: '123' accKey: '123'

View file

@ -28,8 +28,7 @@ describe("Bing Web", function () {
should.not.exist(err); should.not.exist(err);
should.exist(res); should.exist(res);
should.exist(body); should.exist(body);
body.webPages.value.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();
@ -41,8 +40,7 @@ describe("Bing Web", function () {
{ {
top: 5, top: 5,
market: 'en-US', market: 'en-US',
adult: 'Strict', adult: 'Strict'
options: ['DisableLocationDetection', 'EnableHighlighting']
}, },
function (err, res, body) { function (err, res, body) {
@ -50,18 +48,18 @@ describe("Bing Web", function () {
should.exist(res); should.exist(res);
should.exist(body); should.exist(body);
body.d.results.should.have.length(5); body.webPages.value.should.have.length(5);
done(); done();
}); });
}); });
it('finds ukrainian results', function(done){ it('finds russian results', function(done){
Bing.web('"Sony Xperia Z3" огляди тест', Bing.web('"Sony Xperia Z3" смартфон',
{ {
top: 5, top: 5,
skip: 0, skip: 0,
market: 'uk-UA' market: 'ru-RU'
}, },
function (err, res, body) { function (err, res, body) {
@ -69,11 +67,11 @@ describe("Bing Web", function () {
should.exist(res); should.exist(res);
should.exist(body); should.exist(body);
body.d.results.should.have.length(5); body.webPages.value.should.have.length(5);
done(); done();
}); });
}) })
}); });
@ -87,19 +85,14 @@ describe("Bing Images", function () {
Bing.images('pizza', Bing.images('pizza',
{ {
top: 3, top: 3,
adult: 'Off', adult: 'Off'
imageFilters: {
size: 'small',
color: 'monochrome'
}
}, },
function (err, res, body) { 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.value.should.have.length(3);
body.d.results.should.have.length(3);
done(); done();
}); });
@ -114,10 +107,9 @@ describe("Bing News", function () {
it('finds news with specific options', function (done) { it('finds news with specific options', function (done) {
Bing.news('ps4', Bing.news('microsoft',
{ {
skip: 1, top: 5
newSortBy: 'Date'
}, },
function (err, res, body) { function (err, res, body) {
@ -127,7 +119,7 @@ describe("Bing News", function () {
should.exist(res); should.exist(res);
should.exist(body); should.exist(body);
body.d.results.should.have.length(15); body.value.should.be.instanceof(Array);
done(); done();
}); });
@ -144,9 +136,7 @@ describe("Bing Composite", function () {
Bing.composite('animal', Bing.composite('animal',
{ {
sources: 'web+news', top: 1,
skip: 1,
newSortBy: 'Date'
}, },
function (err, res, body) { function (err, res, body) {
@ -156,7 +146,7 @@ describe("Bing Composite", function () {
should.exist(res); should.exist(res);
should.exist(body); should.exist(body);
body.d.results.should.have.length(1); body.webPages.value.should.have.length(1);
done(); done();
}); });
@ -173,12 +163,7 @@ describe("Bing Video", function () {
Bing.video('monkey vs frog', Bing.video('monkey vs frog',
{ {
top: 10, top: 10
videoFilters: {
duration: 'short',
resolution: 'high'
},
videoSortBy: 'Date'
}, },
function (err, res, body) { function (err, res, body) {
@ -186,7 +171,7 @@ describe("Bing Video", function () {
should.exist(res); should.exist(res);
should.exist(body); should.exist(body);
body.d.results.should.have.length(10); body.value.should.have.length(10);
//TODO try here unaccepted options like imageFilters //TODO try here unaccepted options like imageFilters
@ -203,14 +188,17 @@ describe("Bing Related Search", function () {
it('finds related search suggestions', function (done) { it('finds related search suggestions', function (done) {
Bing.relatedSearch('berlin', Bing.relatedSearch('berlin',
{ top: 5, market: 'en-US' }, {
top: 5,
market: 'en-US'
},
function (err, res, body) { 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(5); body.webPages.value.should.have.length(5);
done(); done();
}); });
@ -232,11 +220,10 @@ describe("Bing Spelling Suggestion", function () {
should.exist(body); should.exist(body);
// Find at leas one suggestion // Find at leas one suggestion
body.d.results.length.should.be.aboveOrEqual(1); body.flaggedTokens.suggestions.length.should.be.aboveOrEqual(1);
body.d.results[0].Value.should.equal("awesome spell"); body.flaggedTokens.suggestions[0].suggestion.should.equal("awesome spell");
done(); done();
}); });
}); });
}); });