Skip to content

Implementation of multiple words in a single request #121

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,92 @@ https://api.dictionaryapi.dev/api/v2/entries/en/hello, result returned will be,
]
```

There is also the option of adding multiple words in a single request by separating them with commas
The following example request https://api.dictionaryapi.dev/api/v2/entries/en/banana,orange would return the following
```json
[
{
"word": "banana",
"phonetic": "bəˈnɑːnə",
"phonetics": [
{
"text": "bəˈnɑːnə",
"audio": "//ssl.gstatic.com/dictionary/static/sounds/20200429/banana--_gb_1.mp3"
}
],
"origin": "late 16th century: via Portuguese or Spanish from Mande.",
"meaning": {
"noun": [
{
"definition": "a long curved fruit which grows in clusters and has soft pulpy flesh and yellow skin when ripe.",
"example": "a bunch of bananas",
"synonyms": [],
"antonyms": []
},
{
"definition": "the tropical and subtropical palmlike plant that bears bananas, having very large leaves but lacking a woody trunk.",
"synonyms": [],
"antonyms": []
}
],
"adjective": [
{
"definition": "insane or extremely silly.",
"example": "I've spent two months in a studio—I must be bananas",
"synonyms": [],
"antonyms": []
}
]
}
},
{
"word": "orange",
"phonetic": "ˈɒrɪn(d)ʒ",
"phonetics": [
{
"text": "ˈɒrɪn(d)ʒ",
"audio": "//ssl.gstatic.com/dictionary/static/sounds/20200429/orange--_gb_1.mp3"
}
],
"origin": "late Middle English: from Old French orenge (in the phrase pomme d'orenge ), based on Arabic nāranj, from Persian nārang .",
"meaning": {
"noun": [
{
"definition": "a large round juicy citrus fruit with a tough bright reddish-yellow rind.",
"example": "eat plenty of oranges",
"synonyms": [],
"antonyms": []
},
{
"definition": "the leathery-leaved evergreen tree that bears the orange, native to warm regions of South and SE Asia. Oranges are a major commercial crop in many warm regions of the world.",
"synonyms": [],
"antonyms": []
},
{
"definition": "a bright reddish-yellow colour like that of the skin of a ripe orange.",
"example": "tones of golden brown and orange",
"synonyms": [],
"antonyms": []
},
{
"definition": "a butterfly with mainly or partly orange wings.",
"synonyms": [],
"antonyms": []
}
],
"adjective": [
{
"definition": "reddish yellow.",
"example": "there was an orange glow in the sky",
"synonyms": [],
"antonyms": []
}
]
}
}
]
```

### Regarding V1 Version
The API earlier use to send response as shown below, but this structure of response was found out to be difficult to work with (you can take a look at these tickets [#32](https://github.com/meetDeveloper/freeDictionaryAPI/issues/32) and [#4](https://github.com/meetDeveloper/freeDictionaryAPI/issues/4)), based on feedback in these tickets I have updated the API to _v2_ version. That said, _v1_ version will always be supported for backward compatibility.

Expand Down
35 changes: 22 additions & 13 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ const { JSDOM } = require('jsdom'),
V1 = 'v1',
V2 = 'v2',

//Word separator
wordSplitCharacter = ",",

// Status Codes
REQUEST_TYPE_STATUS_CODE = {
notFound: 404,
Expand Down Expand Up @@ -66,17 +69,17 @@ app.set('trust proxy', true);

app.use(limiter);

app.get('/api/:version/entries/:language/:word', async (req, res) => {
let { word, language, version } = req.params,
app.get('/api/:version/entries/:language/:words', async (req, res) => {
let { words, language, version } = req.params,
include = _.reduce(_.get(req.query, 'include', '').split(','), (accumulator, current) => {
accumulator[current] = true;

return accumulator;
}, {});

word = decodeURIComponent(word);
words = decodeURIComponent(words);

if (!word || !language || !version) {
if (!words || !language || !version) {
return handleError.call(res, new errors.NoDefinitionsFound());
}

Expand All @@ -93,18 +96,23 @@ app.get('/api/:version/entries/:language/:word', async (req, res) => {
// @todo: Find better error.
if (!utils.isLanguageSupported(language)) { return handleError.call(res, new errors.NoDefinitionsFound()); }

word = word.trim().toLocaleLowerCase(language);

words = words.trim().toLocaleLowerCase(language);
let wordList = words.split(wordSplitCharacter);

try {
let definitions = await dictionary.findDefinitions(word, language, { include }),
status = 200,
body;
let wordsDefinitions = [];

await Promise.all(wordList.map(async (word) => {
let definitions = await dictionary.findDefinitions(word, language, { include })

if (version === V1) {
definitions = dictionary.transformV2toV1(definitions);
}

if (version === V1) {
definitions = dictionary.transformV2toV1(definitions);
}
wordsDefinitions.push(definitions[0]);
}));

body = JSON.stringify(definitions, (key, value) => {
let body = JSON.stringify(wordsDefinitions, (key, value) => {
if (typeof value === 'object') { return value; }

return cleanText(value);
Expand All @@ -113,6 +121,7 @@ app.get('/api/:version/entries/:language/:word', async (req, res) => {
res.set(HEADER_CONTENT_TYPE, 'application/json');
res.set(HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, '*');

let status = 200;
return res.status(status).send(body);
} catch (error) {
return handleError.call(res, error);
Expand Down