NodeJS web service with standalone DB, coded in TypeScript using Express & BetterSQLite

Gautam Panickar SS
3 min readSep 5, 2022

I wish I could write an intro, but there isn’t much to talk about. The writing will be more of code and less text, as Ibelieve my code is self-explanatory 😉 . I am assuming the readers to have a minimum knowledge in TypeScript & ExpressJS.

It is not necessary that you follow this project structuring or style.

The project directory structure

Because you’ll be coding in TypeScript. Given below is it’s config file. My root directory is named as app for personal convenience.

Note that my include key in tsconfig.json consists of the following. This is essential for the compiler to pick up all the .ts files in the sub directories of app directory.

"compilerOptions": {
...
"outDir": "./dist",
"baseUrl": "./app",
...
},
"include": [ "./app/**/*" ]

Note that output files are transferred to directory name dist .

Before working on the code, lets start installing all the required npm modules.

npm i typescript express @types/express better-sqlite3 nodemon ts-node body-parser 

In the package.json file, note the following keys.

...
"main": "dist/server.js",
"scripts": {
"compile": "tsc",
"start": "nodemon ./dist/server.js",
"compile-and-start": "npm run compile && npm run start",
}
...

Here, note that the entry point to the main file is specified as server.js in dist directory. When compile script is executed, the .ts files in sub-directories of app is compiled into .js files and the output is stored in dist directory. Therefore, server.js is the compiled form of server.ts that we will discuss later.

Also note that we use nodemon for kicking a local server.

Moving to the bottom of the stack, which is database. We have used better-sqlite3 , which is a library based on SQLite, that claims to offer some efficient querying capabilities. The syntax is pretty much similar to SQLite. You may dig into the docs to find more about it. A simple service is coded with methods to initialise the DB and then read/add data from/into it.

database-service.ts

The DB name is set to hurray.db . Set verbose: console.log while initialising the DB to view the complete queries run against the DB on console. This could be useful while debugging.

Let’s code the server now. The code for server.ts is similar to that of every Node-ExpressJS application.

server.ts

Note that the port number is hard-coded. You can also see that, DB initialisation happens here, which involves the creation of tables. Another important step to note is the App class. This is the main class of the web service/app that we are creating.

app.ts

It is important to understand how the above class is exported. I am exporting a new instance of the app.

export default new App([new UserController()]).app;

I have implemented CORS whitelisting. So, if you want to go raw, remove the white-listing logic and use

res.header('Access-Control-Allow-Origin', '*');

We can have multiple controllers. UserController is the one handling user API endpoints. I also have a type declared for the controllers, which is a good practice while coding in TS. Express is incomplete without middlewares, we have an error ErrorMiddleWare for handling the errors.

errormiddleware.ts

Here, HttpException is a custom type that extends the default Error .

The UserController maps to routes user/info , user/save . Express router provides all the http methods to deal with the different cases. I have sued get for user/info and post for user/save .

user-controller.ts

The errors in the controller methods will be handled by the middleware we wrote before. You can see that the business logic is written in UserService . Let’s dive into see what is in there.

user-service.ts

I am only expecting a single row in the UserInfo table. Hence, the above logic is used. Also, there is a couple of custom exceptions in use, which is easily replicable.

This is all the code you need to get started. Once finished, run

npm run compile-and-start

This will build and start a dev server listening on port 66666. You will also find the DB file named hurray.db in the root directory. Play with Postman or cURL to test the APIs.

--

--