node-onesky-utils
Version:
Node.js utils for working with OneSky translation service. Original package from @brainly/onesky-utils
98 lines (88 loc) • 2.93 kB
JavaScript
var queryString = require('querystring')
var FormData = require('form-data')
var fs = require('fs')
var _private = rootRequire('lib/privateFunctions.js')
var _globals = rootRequire('lib/globals.js')
var apiAddress = _globals.apiAddress
/**
* Post translations file form service
* @param {Object} options
* @param {Number} options.projectId Project ID
* @param {String} options.format File format (see documentation)
* @param {String} options.content File to upload
* @param {Boolean} options.keepStrings Keep previous, non present in this file strings
* @param {String} options.secret Private key to OneSky API
* @param {String} options.apiKey Public key to OneSky API
* @param {String} options.language Language of the uploaded file
* @param {String} options.fileName Name of the uploaded file
*/
function postFile(options) {
options.hash = _private.getDevHash(options.secret)
return _private.makeRequest(
_getUploadOptions(options),
'Unable to upload document'
)
}
/**
* @param {Object} options
* @return {Object}
* @private
*/
function _getUploadOptions(options) {
const form = new FormData()
// Add file to FormData - handle different types of content
if (typeof options.content === 'string') {
// If it's a string content
form.append('file', Buffer.from(options.content), {
filename: options.fileName,
contentType: 'application/octet-stream'
})
} else if (Buffer.isBuffer(options.content)) {
// If it's a Buffer
form.append('file', options.content, {
filename: options.fileName,
contentType: 'application/octet-stream'
})
} else if (options.content && typeof options.content === 'object' && options.content.path) {
// If it's a file path or readable stream
form.append('file', fs.createReadStream(options.content.path), {
filename: options.fileName
})
} else {
// Default case, try to use as is
form.append('file', options.content, {
filename: options.fileName
})
}
// Add other form fields
form.append('api_key', options.apiKey)
form.append('dev_hash', options.hash.devHash)
form.append('file_format', options.format)
form.append('is_keeping_all_strings', options.keepStrings.toString())
form.append('locale', options.language)
form.append('timestamp', options.hash.timestamp.toString())
form.append('is_allow_translation_same_as_original', (
options.allowSameAsOriginal || false
).toString())
// Get form headers
const formHeaders = form.getHeaders()
return {
method: 'POST',
url:
apiAddress +
'/1/projects/' +
options.projectId +
'/files?' +
queryString.stringify({
api_key: options.apiKey,
timestamp: options.hash.timestamp,
dev_hash: options.hash.devHash
}),
data: form,
headers: {
...formHeaders
}
}
}
module.exports = postFile