How to Use PureORM: A Guide to Object-Relational Mapping

Sep 8, 2024 | Programming

Welcome to our comprehensive guide on using PureORM, a lightweight Object-Relational Mapping (ORM) tool that promises to simplify the way you work with databases in JavaScript. Whether you’re building a new project from scratch or integrating an ORM into your current setup, this article will provide you with a user-friendly breakdown of the process. Let’s dive in!

What is PureORM?

PureORM is designed to bridge the gap between raw SQL queries and structured business objects. Instead of the typical database-connected stateful objects, PureORM allows you to write native SQL and receive well-structured, nested pure instances of your business classes. This approach enables you to maintain the purity and integrity of your data models, focusing on business logic rather than database intricacies.

Getting Started: Installation Steps

To get started with PureORM, follow these simple steps.

Step 1: Installing PureORM

First, make sure to install PureORM along with your preferred database driver. The following command is suitable for PostgreSQL:

npm install --save pure-orm
npm install --save pg-promise

Step 2: Creating Business Objects

Next, you’ll need to define your business objects that correspond to your database tables. Here’s a quick analogy to keep it simple: think of your database as a library. Each book in this library represents a table, and each chapter represents an object within that table. You’ll be creating the summaries of these chapters in the form of model classes.

Your models may look something like this:

import { IModel, IEntity, IColumns } from 'pure-orm';

export const tableName: string = 'person';
export const columns: IColumns = ['id', 'name'];

export class Person implements IModel {
  id: number;
  name: string;
  
  constructor(props) {
    this.id = props.id;
    this.name = props.name;
  }
}

export const personEntity: IEntity = { tableName, columns, Model: Person };

Step 3: Setting Up Your Database Driver

To connect PureORM to your database, you must create a connection object.

import pgPromise from 'pg-promise';

const pgp = pgPromise();
const connectionObject = {
  host: process.env.DB_HOSTNAME,
  port: process.env.DB_PORT,
  database: process.env.DB_NAME,
  user: process.env.DB_USERNAME,
  password: process.env.DB_PASSWORD
};

export const db = pgp(connectionObject);

Step 4: Creating Your ORM

Now that the database driver is configured, you can create your ORM instance.

import { create } from 'pure-orm';
import { personEntity } from './models/person';

const orm = create({
  entities: [personEntity],
  db
});

export default orm;

Step 5: Implementing Data Access Layer

Your data access function will enable you to retrieve a person’s data with ease:

import orm from '../factories/orm';
import { Person } from '../models/person';

export const getPerson = (id: number): Person => {
  const query = `SELECT * FROM person WHERE id = $(id)`;
  return orm.one(query, { id });
};

Step 6: Writing Your Controller Code

Finally, connect everything in your controller:

import express, { Request, Response } from 'express';
import { getPerson } from './data-access/person';

const app = express();
const port = process.env.PORT;

app.get('/person/:id', (req: Request, res: Response) => {
  const person = getPerson(Number(req.params.id));
  res.json(person);
});

app.listen(port);

Troubleshooting Common Issues

  • Database Connection Errors: Ensure that your connection settings in the `.env` file are accurate. Double-check your database host, user credentials, and that your database server is running.
  • Error Handling: If you encounter issues with queries, use error handlers in your `orm.one()` methods to catch and handle specific errors in a more user-friendly way.
  • Data Structure Mismatches: Verify that the names of your columns in the SQL queries correspond exactly with the property names in your model classes to avoid undefined values.

For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.

Conclusion

PureORM offers you a clean and effective way to interact with your relational databases while maintaining the integrity of your business models. By allowing you to write raw SQL and returning structured objects, you can focus on what truly matters – your business logic.

At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.

Next Steps

Now that you have a solid understanding of PureORM, consider experimenting with additional CRUD operations or integrating it into a larger application. Happy coding!

Stay Informed with the Newest F(x) Insights and Blogs

Tech News and Blog Highlights, Straight to Your Inbox