Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PubNub Clarifai Image Analysis BLOCK
const xhr = require('xhr');
const query = require('codec/query_string');
const store = require('kvstore');
export default (request) => {
const clientId = 'YOUR_ID';
const clientSecret = 'YOUR_SECRET';
const apiUrl = 'https://api.clarifai.com/v1/tag';
const tokenUrl = 'https://api.clarifai.com/v1/token';
const getToken = () => {
const payload = query.stringify({
client_id: clientId,
client_secret: clientSecret,
grant_type: 'client_credentials'
});
const httpOptions = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json'
},
body: payload,
method: 'post'
};
return xhr.fetch(tokenUrl, httpOptions)
.then(r => {
const body = JSON.parse(r.body || r);
return store.set('access_token', body.access_token).then(() => {
return body.access_token;
});
});
};
const getResult = (accessToken) => {
const queryParams = {
access_token: accessToken,
url: request.message.url
};
return xhr.fetch(apiUrl + '?' + query.stringify(queryParams))
.then((r) => {
const body = JSON.parse(r.body || r);
if (body.status_code && body.status_code === 'TOKEN_EXPIRED') {
return store.set('access_token', null).then(() => {
return getResult(getToken());
});
}
request.message.analysis = body;
return request.ok();
})
.catch((e) => {
console.error(e);
});
};
return store.get('access_token').then((accessToken) => {
if (!accessToken) {
return getResult(getToken());
} else {
return getResult(accessToken);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment