-
Notifications
You must be signed in to change notification settings - Fork 1
/
fsabg.js
55 lines (51 loc) · 2.25 KB
/
fsabg.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
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
// Yes, we're only using the postcode.
// Yes, I could extract it separately, but I'm leaving it open to all in case we
// can amend this in future.
var bizName = request.name;
var bizAddress = [ request.street, request.city, request.postcode ];
var bizAddressString = bizAddress[2];
var apiBase = 'http://api.ratings.food.gov.uk/';
// Check we haven't received empty strings...
if (( bizName === '' && bizAddress === '' ) === false) {
// Build our full API URL.
var apiCall = 'Establishments?name=' + encodeURIComponent(bizName) + '&address=' + encodeURIComponent(bizAddressString);
var apiUrl = apiBase + apiCall;
$.ajax({
beforeSend: function(request, settings) {
// The FSA API requires you to set this header to work.
request.setRequestHeader('x-api-version', 2);
},
dataType: 'json',
url: apiUrl
})
.done(function(data, status) {
var jsonMsg;
// Check we've actually received some results!
var resultCount = Object.keys(data.establishments).length;
if ( resultCount === 1 ) {
jsonMsg = {
'success': true,
'rating': data.establishments[0].RatingValue,
'key': data.establishments[0].RatingKey,
'date': data.establishments[0].RatingDate,
'results': resultCount
};
} else {
jsonMsg = {
'success': false,
'results': resultCount
};
}
sendResponse(jsonMsg);
})
.fail(function(data, status, error) {
console.log('Call to API failed: ' + status);
sendResponse({ 'success': false });
});
} else {
sendResponse({ 'success': false });
}
return true;
});