Setting up TypeORM with Javascript and Express

We are a community of developers, designers, and marketers. We are journaling every experience and step we take in our pursuit for growth and nurturing.
Search for a command to run...

We are a community of developers, designers, and marketers. We are journaling every experience and step we take in our pursuit for growth and nurturing.
No comments yet. Be the first to comment.
As a tech professional, you probably spend most of your day sitting in front of a computer. While this may be great for your career, it's not so great for your health. But don't worry, there's a simple solution: EXERCISE! Recently I've been going to ...

In today's rapidly evolving world, staying ahead requires constant upskilling and innovation. The Renaissance Innovation Labs or RILearn Bootcamp stands as a beacon of opportunity, offering comprehensive skill development that goes beyond traditional...

Introduction In the face of the current economic downturn affecting various industries, including the tech sector, companies and individuals must adapt and find ways to thrive in these challenging times. In this blog post, we will discuss effective s...

Introduction Are you a freelancer, entrepreneur, or remote worker looking for a lively coworking space in Port Harcourt, Nigeria to boost your productivity and develop a sense of community? Look no further than Ubuntu Space, a thriving and innovative...
In the past few years, technology has made significant progress, and it's now striving to establish gender balance. There is a concerted effort to explore technology's potential to enable women to live their lives with the same freedom and opportunit...

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).
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.
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.
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
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