description and source-codegoogle-translate = function (apiKey, newConcurrentLimit) {
// Set new concurrent limit for async calls if specified
concurrentLimit = newConcurrentLimit || concurrentLimit;
var get = getRequestWithApi(apiKey),
post = postRequestWithApi(apiKey),
api = {};
// TRANSLATE
api.translate = function(strings, sourceLang, targetLang, done) {
if (typeof strings !== 'string' && !Array.isArray(strings)) return done('Input source must be a string or array of strings');
if (typeof sourceLang !== 'string') return done('No target language specified. Must be a string');
// Make sourceLang optional
if (!done) {
done = targetLang;
targetLang = sourceLang;
sourceLang = null;
}
if (!_.isFunction(done)) return console.log('No callback defined');
// Split into multiple calls if string array is longer than allowed by Google (5k for POST)
var stringSets;
if (shouldSplitSegments(strings)) {
stringSets = [];
splitArraysForGoogle(strings, stringSets);
} else if (!Array.isArray(strings)) {
stringSets = [[strings]];
} else {
stringSets = [strings];
}
// Request options
var data = { target: targetLang };
if (sourceLang) data.source = sourceLang;
// Run queries async
async.mapLimit(stringSets, concurrentLimit, function(stringSet, done) {
post('', _.extend({ q: stringSet }, data), parseTranslations(stringSet, done));
}, function(err, translations) {
if (err) return done(err);
// Merge and return translation
translations = _.flatten(translations);
if (translations.length === 1) translations = translations[0];
done(null, translations);
});
};
// GET SUPPORTED LANGUAGES
api.getSupportedLanguages = function(target, done) {
// Data param is optional
if (_.isFunction(target)) {
done = target;
target = {};
} else {
target = { target: target };
}
if (!_.isFunction(done)) return console.log('No callback defined');
get('languages', target, parseSupportedLanguages(done));
};
// DETECT LANGUAGES
api.detectLanguage = function(strings, done) {
if (!done) return console.log('No callback defined');
if (typeof strings !== 'string' && !Array.isArray(strings)) return done('Input source must be a string or array of strings');
// Split into multiple calls if string array is longer than allowed by Google (5k for POST)
var stringSets;
if (shouldSplitSegments(strings)) {
stringSets = [];
splitArraysForGoogle(strings, stringSets);
} else if (!Array.isArray(strings)) {
stringSets = [[strings]];
} else {
stringSets = [strings];
}
// Run queries async
async.mapLimit(stringSets, concurrentLimit, function(stringSet, done) {
post('detect', { q: stringSet }, parseLanguageDetections(stringSet, done));
}, function(err, detections) {
if (err) return done(err);
// Merge arrays and return detections
detections = _.flatten(detections);
if (detections.length === 1) detections = detections[0];
done(null, detections);
});
};
////
// RETURN API
////
return {
translate: api.translate,
getSupportedLanguages: api.getSupportedLanguages,
detectLanguage: api.detectLanguage
};
}