Insight into some TypeORM Features

Etiene JamesEtiene James
5 min read

In continuation of our previous topic on "Introduction to TypeORM and its Features", you can read about it here. We will be having an insight into some of those features mentioned.

Just as a reminder of what TypeORM is, we defined it to be an open-source Object-Relational Mapping (ORM) library for TypeScript and JavaScript. And It provides a powerful set of tools for working with relational databases, such as MySQL, PostgreSQL, SQLite, and Microsoft SQL Server.

A list of some of the features are:

  • Logging

  • TypeScript support

  • Migrations

  • Transactions

  • Event System

  • Caching

  • Query Builder

Now, please take a front seat as we ride the waves of knowledge into the pleasurable sea of wonders of what TypeORM as a library has in store for us, which we can use to create magical potions of 1s and 0s.

excitement

Logging

The logging feature in TypeORM gives developers the superpower to SQL statements or queries executed by the Entity Manager to be logged into the console. The benefit of this is that it can help in tough times of debugging or checking for the performance of your code.

We can enable the logging feature by simply setting the options in the `ConnectionOptions` configuration object.

Let us see an example below:

import { createConnection } from "typeorm";

createConnection({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "postgres",
    password: "postgres",
    database: "test",
    logging: true
})
    .then(connection => {
        console.log("TypeORM logging enabled");
    })
    .catch(error => console.log(error));

We can see that the logging feature in the example given above is enabled by setting it to true . Let's look at a scenario where you decide or are required to log in to a custom location in your project. You can achieve this by writing an SQL statement that runs every time it is being called and executed by the Entity Manager.

Here's an example of how it can be achieved:

import { createConnection } from "typeorm";

createConnection({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "postgres",
    password: "postgres",
    database: "test",
    logging: (sql: string) => {
        console.log("SQL statement executed: ", sql);
    }
})
    .then(connection => {
        console.log("TypeORM logging enabled");
    })
    .catch(error => console.log(error));

There are options you can enable to output to the console. Here are the various options available:

  • query

  • error

  • warn

  • info

  • schema

  • log

Here's an example of{ how to enable them

{
...
logging: ["log", "query"] // You can add as many as needed
{

You also get to enable all if you want. Here's an example:

{
...
logging: "all"
{

You can also create a custom logger class by implementing the Logger interface or by extending the AbstractLogger class. We won't be looking deep into that aspect in this article.
Another feature to look into in our next section will be its support for the use of Typescript.

Support for Typescript

TypeORM is a popular Object Relational Mapping (ORM) library that provides support for TypeScript and JavaScript. TypeScript is a statically typed superset of JavaScript that adds features such as classes, interfaces, and type annotations to the language.

TypeORM was built specifically to support TypeScript, and it provides a variety of features to take advantage of TypeScript's type system. For example, TypeORM allows you to define entities using classes and interfaces, and it uses the TypeScript type system to validate the entities and their relationships at runtime.

TypeORM also provides a number of type definitions for its API, allowing developers to take advantage of TypeScript's IntelliSense and type-checking features when using TypeORM in their applications.

Overall, TypeORM provides robust support for TypeScript and allows developers to write clean, maintainable code when working with databases in their TypeScript applications.

The next section will be dealing with Query Caching.

Query Caching in Typeorm

TypeORM does not have built-in support for query caching. However, it is possible to implement query caching in TypeORM by using a caching library such as node-cache or lru-cache in conjunction with TypeORM.

Here's an example of how you might implement query caching in TypeORM:

typescriptCopy codeimport { createConnection, EntityManager, getConnection } from "typeorm";
import * as NodeCache from "node-cache";

const queryCache = new NodeCache();

const cacheKey = (query: string, params: any[]): string => {
  return `${query}:${JSON.stringify(params)}`;
};

const getCachedQuery = async (
  manager: EntityManager,
  query: string,
  params: any[]
) => {
  const key = cacheKey(query, params);
  const cachedResult = queryCache.get(key);
  if (cachedResult) {
    return cachedResult;
  }

  const result = await manager.query(query, params);
  queryCache.set(key, result);

  return result;
};

createConnection().then(async connection => {
  const manager = getConnection().manager;
  const result = await getCachedQuery(manager, "SELECT * FROM users", []);
  console.log(result);
});

In this example, we're using the node-cache library to implement a simple query cache. The getCachedQuery function first checks if the result of the query is already in the cache, and if it is, it returns the cached result. If the result is not in the cache, it executes the query using the EntityManager and caches the result for future use.

It's important to note that this is just one way to implement query caching in TypeORM and that different caching strategies may be more appropriate for different use cases. For example, you may want to cache results for a limited time or based on the size of the result set.

We were able to see some of the features and examples of how to implement them. We saw that TypeORM was built specifically to support Typescript as it allows you to define entities using classes and interfaces, and uses the TypeScript type system to validate the entities and their relationships at runtime. Here's a recommendation for further reading:

I would love to connect with you on Twitter and get to hear your thoughts in the comments section. Thanks for reading.

0
Subscribe to my newsletter

Read articles from Etiene James directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Etiene James
Etiene James

I am a Software Engineer, Tech Writer based in Lagos, Nigeria. I am passionate about solving problems, sharing knowledge gained during my Tech journey, and excited in meeting people.