Last active
November 22, 2016 05:43
-
-
Save sunnygleason/c6673fb3d316096d0f69150f1ad3b1a4 to your computer and use it in GitHub Desktop.
PubNub Clarifai Image Analysis BLOCK
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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