Setting up TypeORM with Javascript and Express

Setting up TypeORM with Javascript and Express

Hi there, in this article I'll be showing you how to spin up a simple boilerplate using Javascript, Express, and TypeORM.

This article assumes that you already know Javascript and have Postgresql installed on your PC. Before jumping into the code, let's see a quick overview of the main libraries used (install them with NPM).

Express JS

This is a library that sits on top of Node JS as a layer of abstraction which makes performing certain tasks with Node JS a lot more straightforward i.e creating a server and handling requests and responses.

Postgresql

This is an open-source relational database management system with over 15 years of active development. It's a very popular database used in modern-day software applications.

TypeORM

This is a trendy Object Relational Mapper that supports many databases such as MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, and WebSQL. It acts as a layer of abstraction making it easy for us to write our database queries and connection code. To start, navigate to any convenient directory on your local machine and run

npm init -y

Nodemon

This is a tool that will help us in our development process by automatically restarting our server every time we make a change to a file and save it.

Next, we'll install all the dependencies needed for this start-up and run,

npm install express pg typeorm nodemon

Next, we'll create a postEntity.js file where we'll define our post schema so

const { EntitySchema } = require('typeorm');

const postSchema = new EntitySchema({
  name: 'Post',
  tableName: 'posts',

  columns: {
    id: { primary: true, type: 'text', generated: 'uuid' },

    title: { type: 'varchar' },

    body: { type: 'text' },

    createdAt: {
      type: 'timestamp',
      default: new Date().toISOString().split('T')[0],
    },
  },
});

module.exports = postSchema;

Next, we'll create a db.js file where we'll configure our database using TypeORM's data source like;

const { DataSource } = require('typeorm');
const Post = require('./postEntity');

const dataSource = new DataSource({
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'postgres',
  password: proccess.env.DB_PASSWORD // The password you created when installing postgresql 
  database: 'blog',
  synchronize: true,
  entities: [Post],
});

dataSource.initialize().then(() => console.log('connected to DB succesfully!'));

module.exports = dataSource;

Next, we'll set up a base app.js file as an entry to our application and write a simple endpoint for our post resource;

const express = require('express');
const dataSource = require('./db.js');
const postRepository = dataSource.getRepository(Post);

const app = express();

app.use(express.json());

//Get All Posts
app.get('/post', async (req, res) => {
  const posts = await postRepository.find();

  res.status(200).json({
    status: 'success',
    posts,
  });
});

//Create Post
app.post('/post', async (req, res) => {
  const doc = postRepository.create(req.body);

  const post = await postRepository.save(doc);

  res.status(200).json({
    status: 'success',
    post,
  });
});

//Update A Single Sost
app.patch('/post/:id', async (req, res) => {
  const post = await postRepository.update({ id: req.params.id }, req.body);

  res.status(200).json({
    status: 'success',
    post,
  });
});

//Get Back A Single Post
app.get('/post/:id', async (req, res) => {
  const post = await postRepository.findBy({ id: req.params.id });

  res.status(200).json({
    status: 'success',
    post,
  });
});

//Delete Single Post
app.get('/post/:id', async (req, res) => {
  const post = await postRepository.delete({ id: req.params.id });

  res.status(200).json({
    status: 'success',
    post,
  });
});    

module.exports = app;

Finally, we create a server.js file where we'll create our express server running on a particular port

const app = require('./app');

const PORT = procces.env.port || 5000

app.listen(PORT, () => {
  console.log('Server Listining in port 5000...');
});

That's it everyone, at this point we can go ahead and test our simple rest API on postman!

In our package.json file, let's quickly add a start script

"scripts": {
    "start": "nodemon server.js"
  },

Now in our terminal, we can run

npm start