forked from cravindra/pexels-api-wrapper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
66 lines (61 loc) · 2.02 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
var fetch = require('node-fetch');
var BASE_URL = "https://api.pexels.com/v1/";
var DIRECTORY = {
SEARCH_URL: BASE_URL + "search",
POPULAR_URL: BASE_URL + "popular"
};
/**
* Pexels API wrapper which exposes Promise factories to interact with the Pexels API endpoints
* @param {string} apiKey API Key provided by Pexels (Required)
*/
function PexelsApi(apiKey) {
if (!apiKey) {
throw new Error("API Key missing");
}
var self = this;
self.apiKey = apiKey;
self.headers = {
'Authorization': apiKey
};
}
/**
* Promise factory to interact with Pexels Search API
* @param {string} query Search term
* @param {number} perPage Specifies the number of items per page (Defaults to 10)
* @param {page} page Specifies the page being requested (Defaults to 1)
*/
PexelsApi.prototype.search = function (query, perPage, page) {
var self = this;
var url = DIRECTORY.SEARCH_URL +
"?query=" + (query ? encodeURIComponent(query) : "") +
"&per_page=" + (perPage && !isNaN(perPage) ? +perPage : 10) +
"&page=" + (page && !isNaN(page) ? +page : 1);
return fetch(url, {
headers: self.headers
})
.then(function (res) {
return res.json();
}).catch(function (err) {
return Promise.reject(err);
});
};
/**
* Promise factory to interact with Pexels Popular Photos API
* @param {number} perPage Specifies the number of items per page (Defaults to 10)
* @param {page} page Specifies the page being requested (Defaults to 1)
*/
PexelsApi.prototype.getPopularPhotos = function (perPage, page) {
var self = this;
var url = DIRECTORY.POPULAR_URL +
"?per_page=" + (perPage && !isNaN(perPage) ? +perPage : 10) +
"&page=" + (page && !isNaN(page) ? +page : 1);
return fetch(url, {
headers: self.headers
})
.then(function (res) {
return res.json();
}).catch(function (err) {
return Promise.reject(err);
});
};
module.exports = PexelsApi;