Categories
JavaScript APIs

Using Google Translate API in our Node.js App with google-translate-api

The google-translate-api module lets us use the Google Translate API in our server-side JavaScript app.

In this article, we’ll look at how to use this package in our Node.js app.

Installation

We can install the package by running:

npm install @vitalets/google-translate-api

Usage

We can use the translate function that comes with this module to do our translation.

For example, we can write:

const translate = require('@vitalets/google-translate-api');

(async ()=>{
  try {
    const res = await translate('je parle français', { to: 'en' })
    console.log(res.text);
    console.log(res.from.language.iso);
  }
  catch (error){
    console.log(error)
  }
})()

translate returns a promise with the result.

The first argument is the text we want to translate.

The 2nd argument has the to property which is the code of the language we want to translate to.

res.text has the resulting text.

And res.from.language.iso has the code of the language of the text in the first argument.

The Google Translate API works with text that have typos.

For example, we can write:

const translate = require('@vitalets/google-translate-api');

(async ()=>{
  try {
    const res = await translate('I spea French', { from: 'en', to: 'fr' })
    console.log(res.text);
    console.log(res.from.text.autoCorrected);
    console.log(res.from.text.value);
    console.log(res.from.text.didYouMean);
  }
  catch (error){
    console.log(error)
  }
})()

We pass in ‘I spea French’ which has a typo.

from has the language oif the original text.

res.text has the translated result without the typo.

res.from.text.autoCorrected has the boolean to indicate whether the original text was autocorrected.

res.from.text.value has the autocorrected version of the text.

res.from.text.didYouMean is true means the API suggested a correction in the source language.

So we get:

je parle français
true
I [speak] French
false

from the 4 console logs.

We can also add our own language to the list.

For example, we can write:

const translate = require('@vitalets/google-translate-api');
translate.languages['sr-Latn'] = 'Serbian Latin';

(async ()=>{
  try {
    const res = await translate('I spea French', { to: 'sr-Latn' })
    console.log(res.text);
  }
  catch (error){
    console.log(error)
  }
})()

Then we get:

Говорим француски

from the console log.

Proxy

We can make requests via a proxy with this library.

To do this, we write:

const translate = require('@vitalets/google-translate-api');
const tunnel = require('tunnel');

(async ()=>{
  try {
    const res = await translate('I spea French', {
      to: 'fr',
      agent: tunnel.httpsOverHttp({
        proxy: {
          host: '138.68.60.8',
          proxyAuth: 'user:pass',
          port: '8080',
          headers: {
            'User-Agent': 'Node'
          }
        }
      })
    })
    console.log(res.text);
  }
  catch (error){
    console.log(error)
  }
})()

We use the tunnel library to make requests over a proxy.

We call the tunnel.httpOverHttp method with the proxy options and credentials to make the translate request over a proxy.

Conclusion

We can use the google-translate-api module lets us use the Google Translate API in our server-side JavaScript app.

Categories
JavaScript APIs

IndexedDB Manipulation with Dexie — Sorting, Iteration, and Keys

IndexedDB is a way to store data in the browser.

It lets us store larger amounts of data than local storage in an asynchronous way.

Dexie makes working with IndexedDB easier.

In this article, we’ll take a look at how to start working with IndexedDB with Dexie.

Reverse the Order of Collection Results

We can reverse the order of the collection results with the reverse method.

For example, we can write:

const db = new Dexie("friends");
db.version(1).stores({
  friends: "id, name, age"
});
(async () => {
  await db.friends.put({
    id: 1,
    name: "jane",
    age: 78
  });
  await db.friends.put({
    id: 2,
    name: "mary",
    age: 76
  });
  const friends = await db.friends
    .toCollection()
    .reverse()
    .toArray()
  console.log(friends)
})()

to get all the items and then reverse the order that’s returned.

Sort By the Given Field

We can call the sortBy method to sort by the given field.

For example, we can write:

const db = new Dexie("friends");
db.version(1).stores({
  friends: "id, name, age"
});
(async () => {
  await db.friends.put({
    id: 1,
    name: "jane",
    age: 78
  });
  await db.friends.put({
    id: 2,
    name: "mary",
    age: 76
  });
  const friends = await db.friends
    .where('age')
    .above(25)
    .sortBy('age');
  console.log(friends)
})()

We sort the results by age with the sortBy method.

Convert Collection to an Array

We can convert a collection to an array with the toArray method.

For instance, we can write:

const db = new Dexie("friends");
db.version(1).stores({
  friends: "id, name, age"
});
(async () => {
  await db.friends.put({
    id: 1,
    name: "jane",
    age: 78
  });
  await db.friends.put({
    id: 2,
    name: "mary",
    age: 76
  });
  const friends = await db.friends
    .where('age')
    .above(25)
    .toArray();
  console.log(friends)
})()

We convert the collection returned by the query methods to a promise with an array with the toArray method.

Get Unique Keys

We can get the unique keys from a collection with the uniqueKeys method.

For instance, we can write:

const db = new Dexie("friends");
db.version(1).stores({
  friends: "id, name, age"
});
(async () => {
  await db.friends.put({
    id: 1,
    name: "jane",
    age: 78
  });
  await db.friends.put({
    id: 2,
    name: "mary",
    age: 76
  });
  const keys = await db.friends
    .toCollection()
    .uniqueKeys()
  console.log(keys)
})()

We call uniqueKeys to get the unique keys from the collection.

We get the id values from the collection.

So we get:

[1, 2]

from the console log.

Stop Iterating Collection Once Given Filter Returns true

We can call the until method to stop iterating a collection once a given filter is true .

For instance, we can use it by writing:

const db = new Dexie("friends");
let cancelled = false;

db.version(1).stores({
  friends: "id, name, age"
});
(async () => {
  await db.friends.put({
    id: 1,
    name: "jane",
    age: 78
  });
  await db.friends.put({
    id: 2,
    name: "mary",
    age: 76
  });
  await db.friends
    .toCollection()
    .until(() => cancelled)
    .each(friend => {
      console.log(friend)
      cancelled = true;
    });
})()

We call until with a callback that returns the value of cancelled .

Then we call each and log the value of friend then we cancelled to true .

So after the first iteration of each , it’ll stop looping through the rest of the collection.

Conclusion

We can sort items, convert items to an array, get unique keys, and stop iteration with the given condition with Dexie.

Categories
JavaScript APIs

IndexedDB Manipulation with Dexie — Offsets, Or, and Raw Results

IndexedDB is a way to store data in the browser.

It lets us store larger amounts of data than local storage in an asynchronous way.

Dexie makes working with IndexedDB easier.

In this article, we’ll take a look at how to start working with IndexedDB with Dexie.

Ignore the First n Items Before the Given Offset

We can call the offset method to return the first n items after the given offset.

For instance, we can use it by writing:

const db = new Dexie("friends");  
db.version(1).stores({  
  friends: "id, name, age"  
});  
(async () => {  
  await db.friends.put({  
    id: 1,  
    name: "jane",  
    age: 78  
  });  
  await db.friends.put({  
    id: 2,  
    name: "mary",  
    age: 76  
  });  
  await db.friends  
    .orderBy('name')  
    .offset(10);  
})()

Then we skip the first 10 results in the collection and include the rest.

Logical OR Operation

We can use the or method to combine 2 conditions together with the logical OR operator in the query.

For instance, we can write:

const db = new Dexie("friends");  
db.version(1).stores({  
  friends: "id, name, age"  
});  
(async () => {  
  await db.friends.put({  
    id: 1,  
    name: "jane",  
    age: 78  
  });  
  await db.friends.put({  
    id: 2,  
    name: "mary",  
    age: 76  
  });  
  const someFriends = await db.friends  
    .where("name")  
    .equalsIgnoreCase("jane")  
    .or("age")  
    .above(40)  
    .sortBy("name")  
  console.log(someFriends)  
})()

We call where with the 'name' argument to query by the name.

And we find the entries with the given name with equalsIgnoreCase .

Then we call or to find the items with the age above 40.

And we call sortBy to sort by the name field.

Get an Array Containing All Primary Keys of the Collection

We can use the primaryKeys method to return a promise with an array of primary keys in the collection.

For instance, we can use it by writing:

const db = new Dexie("friends");  
db.version(1).stores({  
  friends: "id, name, age"  
});  
(async () => {  
  await db.friends.put({  
    id: 1,  
    name: "jane",  
    age: 78  
  });  
  await db.friends.put({  
    id: 2,  
    name: "mary",  
    age: 76  
  });  
  const keys = await db.friends  
    .where("name")  
    .equalsIgnoreCase("jane")  
    .primaryKeys()  
  console.log(keys)  
})()

id is the primary key of each entry.

Then we call primaryKeys to return a promise with the array of primary keys.

Get Raw Results

We can get thee raw results from a query with the raw method.

The results won’t be filtered through the reading hooks.

For instance, we can write:

const db = new Dexie("friends");  
db.version(1).stores({  
  friends: "id, name, age"  
});  
(async () => {  
  await db.friends.put({  
    id: 1,  
    name: "jane",  
    age: 78  
  });  
  await db.friends.put({  
    id: 2,  
    name: "mary",  
    age: 76  
  });  
  const keys = await db.friends  
    .where("name")  
    .equalsIgnoreCase("jane")  
    .raw()  
    .toArray()  
  console.log(keys)  
})()

to use it.

Using raw won’t do things like mapping objects to their mapped class.

Conclusion

We can ignore the first n items from the results, get primary keys, and get raw results from an IndexedDB collection with Dexie.

Categories
JavaScript APIs

IndexedDB Manipulation with Dexie — Modifying and Deleting Items

IndexedDB is a way to store data in the browser.

It lets us store larger amounts of data than local storage in an asynchronous way.

Dexie makes working with IndexedDB easier.

In this article, we’ll take a look at how to start working with IndexedDB with Dexie.

Limiting Number of Results Returned

We can limit the number of results returned with the limit method.

For instance, we can write:

const db = new Dexie("friends");
db.version(1).stores({
  friends: "id, name, age"
});
(async () => {
  await db.friends.put({
    id: 1,
    name: "jane",
    age: 78
  });
  await db.friends.put({
    id: 2,
    name: "mary",
    age: 76
  });
  const someFriends = await db.friends
    .orderBy('name')
    .limit(10)
    .toArray()
  console.log(someFriends)
})()

We call limit with 10 as its argument to limit the number of items to 10.

Modifying Results in a Collection

We can modify results in a collection with the modify method.

To use it, we write:

const db = new Dexie("friends");
db.version(1).stores({
  friends: "id, name, age"
});
(async () => {
  await db.friends.put({
    id: 1,
    name: "jane",
    age: 78
  });
  await db.friends.put({
    id: 2,
    name: "mary",
    age: 76
  });
  await db.friends
    .orderBy('name')
    .modify({
      isBigfoot: true
    });
})()

to get the items in the friends table ordered by the name field.

Then we call modify to add the isBigFoot field and set it to true in each item in the collection.

We can also pass in a function by writing:

const db = new Dexie("friends");
db.version(1).stores({
  friends: "id, name, age"
});
(async () => {
  await db.friends.put({
    id: 1,
    name: "jane",
    age: 78
  });
  await db.friends.put({
    id: 2,
    name: "mary",
    age: 76
  });
  await db.friends
    .orderBy('name')
    .modify(friend => {
      friend.age *= 0.5;
    });
})()

We change the age value of each entry in the collection by multiplying it by 0.5.

Also, we can use the 2nd parameter to reference the result entry.

For instance, we can writeL

const db = new Dexie("friends");
db.version(1).stores({
  friends: "id, name, age"
});
(async () => {
  await db.friends.put({
    id: 1,
    name: "jane",
    age: 78
  });
  await db.friends.put({
    id: 2,
    name: "mary",
    age: 76
  });
  await db.friends
    .orderBy('name')
    .modify((friend, ref) => {
      ref.value = {
        ...ref.value,
        age: 55
      }
    });
})()

We set the ref.value to set the value of the entry to something else.

Also, we can use it to delete an object by using the delete operator.

For example, we can write:

const db = new Dexie("friends");
db.version(1).stores({
  friends: "id, name, age"
});
(async () => {
  await db.friends.put({
    id: 1,
    name: "jane",
    age: 78
  });
  await db.friends.put({
    id: 2,
    name: "mary",
    age: 76
  });
  await db.friends
    .orderBy('name')
    .modify((friend, ref) => {
      delete ref.value;
    });
})()

We just delete the ref.value property to delete an item.

The example above is the same as:

const db = new Dexie("friends");
db.version(1).stores({
  friends: "id, name, age"
});
(async () => {
  await db.friends.put({
    id: 1,
    name: "jane",
    age: 78
  });
  await db.friends.put({
    id: 2,
    name: "mary",
    age: 76
  });
  await db.friends
    .orderBy('name')
    .delete();
})()

Conclusion

We can modify and delete items with the collection’s modify method with Dexie.

Categories
JavaScript APIs

IndexedDB Manipulation with Dexie — Iteration, Filtering, and First and Last Value

IndexedDB is a way to store data in the browser.

It lets us store larger amounts of data than local storage in an asynchronous way.

Dexie makes working with IndexedDB easier.

In this article, we’ll take a look at how to start working with IndexedDB with Dexie.

Loop Through Each Primary or Unique Key

We can loop through each primary or unique with the eachUniqueKey method.

For example, we can write:

const db = new Dexie("friends");
db.version(1).stores({
  friends: "id, name, age"
});
(async () => {
  await db.friends.put({
    id: 1,
    name: "jane",
    age: 78
  });
  await db.friends.put({
    id: 2,
    name: "mary",
    age: 76
  });
  await db.friends
    .orderBy('name')
    .eachUniqueKey(name => console.log(name));
})()

We call eachUniqueKey after calling orderBy with 'name' to get the name value of each entry.

Filter Objects

We can filter objects in a collection with the filter method.

For instance, we can use it by writing:

const db = new Dexie("friends");
db.version(1).stores({
  friends: "id, name, age"
});
(async () => {
  await db.friends.put({
    id: 1,
    name: "jane",
    age: 78
  });
  await db.friends.put({
    id: 2,
    name: "mary",
    age: 76
  });
  const someFriends = await db.friends
    .orderBy('name')
    .filter(({
      age
    }) => age > 76)
    .toArray();
  console.log(someFriends)
})()

We create 2 entries in the friends table.

Then we query the friends table.

And then we call filter with the condition we want to return the items with the given condition.

Get the First Item in a Collection

We can use the first method to get the first item in a collection.

For example, we can write:

const db = new Dexie("friends");
db.version(1).stores({
  friends: "id, name, age"
});
(async () => {
  await db.friends.put({
    id: 1,
    name: "jane",
    age: 78
  });
  await db.friends.put({
    id: 2,
    name: "mary",
    age: 76
  });
  const someFriend = await db.friends
    .orderBy('name')
    .first()
  console.log(someFriend)
})()

first returns a promise with the first item in the result collection, so we get:

{id: 1, name: "jane", age: 78}

in the console log.

Get All Keys of the Collection

We can get all the keys of a collection with the keys method.

For instance, we can write:

const db = new Dexie("friends");
db.version(1).stores({
  friends: "id, name, age"
});
(async () => {
  await db.friends.put({
    id: 1,
    name: "jane",
    age: 78
  });
  await db.friends.put({
    id: 2,
    name: "mary",
    age: 76
  });
  const someFriends = await db.friends
    .orderBy('name')
    .keys()
  console.log(someFriends)
})()

We dcall orderBy with 'name' , so we get all the values of name in the database from the returned promise.

Therefore, we get:

["jane", "mary"]

in the console log.

Get the Last Item from a Collection

The last method letsus get the last item from a collection.

For instance, we can write:

const db = new Dexie("friends");
db.version(1).stores({
  friends: "id, name, age"
});
(async () => {
  await db.friends.put({
    id: 1,
    name: "jane",
    age: 78
  });
  await db.friends.put({
    id: 2,
    name: "mary",
    age: 76
  });
  const someFriends = await db.friends
    .orderBy('name')
    .last()
  console.log(someFriends)
})()

We sorted the results by their name value.

Then we call last to get the last item from the collection.

So we get:

{id: 2, name: "mary", age: 76}

logged in the console.

Conclusion

We can loop throygh items in collections, filter them, or get the first or last item from an IndexedDB collection with Dexie.