Type Safety in Programming: Why It Matters

When it comes to programming, ensuring type safety is crucial. Type safety guarantees that type errors are caught during compilation, preventing unexpected consequences in your application. Unfortunately, JavaScript, a popular programming language, is not strongly typed, which means some type errors may go undetected during development.

The Rise of TypeScript and Slonik

To address this issue, efforts have been made to create flavors of JavaScript that ensure type safety, such as TypeScript. While TypeScript has been well-received by the JavaScript community, we still need a type safety check when writing queries and interacting with our database. This is where Slonik comes in – a Node.js PostgreSQL driver with strict types, detailed logging, and assertions.

Why Choose Slonik?

Unlike ORMs or query builders that have TypeScript enabled, Slonik offers the best of both worlds. You get type safety, assertions, logging, and protection against SQL injections while still having total control over your queries. With Slonik, you can write efficient and complex queries without hindering your learning experience.

Building a Backend App with Slonik

In this tutorial, we’ll build a simple wallet API that allows registered users to send money to each other using their usernames. To get started, you’ll need:

  • Node.js (≥v14.0)
  • Express.js
  • PostgreSQL
  • Slonik
  • Working knowledge of Node.js, TypeScript, and Express

Creating a Database

First, install Postgres on your local machine and create a database. Then, run some queries to create your database tables and attributes.

Setting Up Your Project

Create a new directory for your server and initialize it using npm. Install the required dependencies, including Slonik, and create a tsconfig.json file to specify the compiler options.

Connecting to Your Database

Use Slonik’s createPool method to connect to your database. Provide a connection URI with the configuration below:


const pool = createPool({
connectionString: 'postgresql://username:password@localhost:5432/database',
});

Creating Endpoints

Create your first endpoint to create a user. Import the JSON web token (JWT) and dotenv packages, and create a .env file to store your JWT secret. Then, generate a JWT for the user after creation.


app.post('/users', async (req, res) => {
const { username, email } = req.body;
const result = await pool.query(`INSERT INTO users (username, email) VALUES ($1, $2) RETURNING *`, [username, email]);
const user = result.rows[0];
const token = generateToken(user);
res.json({ user, token });
});

Adding More Endpoints

Create more endpoints using the same principles, with the exception of decoding your token first to ascertain which user is making a request. Add a balance endpoint to add an amount to the balance of users, a user endpoint to get the details of each user, and a transfer endpoint to allow users to transfer amounts to each other.

The Power of Slonik

Slonik is a great Postgres client that offers good type checking using its query methods, while still giving you full control over your queries. Although it isn’t as mature as other Node Postgres clients, it is a solid alternative. With Slonik, you can ensure type safety and write efficient queries without compromising on control.

Leave a Reply

Your email address will not be published. Required fields are marked *