Created
October 18, 2022 06:35
-
-
Save btquanto/701c7ace173d37d70e8d87c91f4f50e2 to your computer and use it in GitHub Desktop.
Rosetta Translation API
This file contains hidden or 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
import fetch from 'node-fetch'; | |
import jwt from 'jsonwebtoken'; | |
const contractId = 'your-contract-id'; | |
const accessKey = 'your-access-key'; | |
const secretKey = 'your-secret'; | |
async function request(url, {method, headers, body}) { | |
console.log('------------------------------'); | |
console.log(`${method}: ${url}`) | |
console.log(`headers:`, headers); | |
console.log(`body:`, body); | |
const res = await fetch(url, { | |
method, | |
headers, | |
body: body ? JSON.stringify(body) : null, | |
}); | |
console.log('------------------------------'); | |
console.log(`RESPONSE <${res.status}>: ${res.status == 200 ? "PASSED" : "FAILED"}`); | |
console.log('------------------------------'); | |
const result = await res.json(); | |
console.log(result); | |
console.log('------------------------------'); | |
console.log('\n\n\n'); | |
return result; | |
} | |
async function getJWT() { | |
const res = await request(`https://translate.rozetta-api.io/api/v1/token`, { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json', | |
}, | |
body: { | |
accessKey: accessKey, | |
secretKey: secretKey, | |
duration: 300, | |
}, | |
}); | |
return res.data.encodedJWT; | |
} | |
function generateJWTToken() { | |
const validDuration = 60 * 30; | |
const payload = { | |
exp: Math.floor(Date.now() / 1000) + validDuration, | |
iss: contractId, | |
accessKey, | |
}; | |
const encodedJWT = jwt.sign(payload, secretKey, { | |
algorithm: 'HS256', | |
}); | |
return encodedJWT; | |
} | |
(async function main(){ | |
/** Main Function */ | |
// const jwtToken = generateJWTToken(); // Alternative | |
const jwtToken = await getJWT(); | |
const texts = ['Hello world']; | |
const sourceLang = 'en'; | |
const targetLang = 'ja'; | |
await request( | |
`https://translate.rozetta-api.io/api/v1/translate`, | |
{ | |
method: "POST", | |
headers: { | |
'Authorization': `Bearer ${jwtToken}`, | |
'Content-Type': 'application/json', | |
}, | |
body: { | |
fieldId: '1', | |
text: texts, | |
sourceLang, | |
targetLang, | |
contractId, | |
} | |
}); | |
})().catch(console.error); |
Author
btquanto
commented
Oct 18, 2022
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment