Examples
Learn by example! Here are common use cases and patterns for FoundryORM.
Express.js Integration
Complete REST API example with Express.js:
server.ts
1import 'reflect-metadata';
2import express from 'express';
3import { Connection, Entity, Column, BaseModel, ConsoleLogger } from 'foundry-orm';
4
5// Define User model
6@Entity('users')
7class User extends BaseModel {
8 @Column('id')
9 id!: number;
10
11 @Column('name')
12 name!: string;
13
14 @Column('email')
15 email!: string;
16
17 @Column('age')
18 age?: number;
19}
20
21const app = express();
22app.use(express.json());
23
24// Initialize database
25async function initDatabase() {
26 const connection = new Connection(
27 'sqlite',
28 { filename: './database.db' },
29 new ConsoleLogger()
30 );
31 await connection.connect();
32 BaseModel.setConnection(connection);
33
34 // Create table
35 await connection.getAdapter().query(`
36 CREATE TABLE IF NOT EXISTS users (
37 id INTEGER PRIMARY KEY AUTOINCREMENT,
38 name TEXT NOT NULL,
39 email TEXT UNIQUE NOT NULL,
40 age INTEGER
41 )
42 `, []);
43}
44
45// Routes
46app.get('/users', async (req, res) => {
47 try {
48 const users = await User.findAll();
49 res.json({ success: true, data: users, count: users.length });
50 } catch (error) {
51 res.status(500).json({ success: false, error: (error as Error).message });
52 }
53});
54
55app.post('/users', async (req, res) => {
56 try {
57 const user = await User.create(req.body);
58 res.status(201).json({ success: true, data: user });
59 } catch (error) {
60 res.status(500).json({ success: false, error: (error as Error).message });
61 }
62});
63
64app.put('/users/:id', async (req, res) => {
65 try {
66 const user = await User.find(parseInt(req.params.id));
67 if (!user) {
68 return res.status(404).json({ success: false, error: 'User not found' });
69 }
70 Object.assign(user, req.body);
71 await user.save();
72 res.json({ success: true, data: user });
73 } catch (error) {
74 res.status(500).json({ success: false, error: (error as Error).message });
75 }
76});
77
78app.delete('/users/:id', async (req, res) => {
79 try {
80 const user = await User.find(parseInt(req.params.id));
81 if (!user) {
82 return res.status(404).json({ success: false, error: 'User not found' });
83 }
84 await user.delete();
85 res.json({ success: true, message: 'User deleted successfully' });
86 } catch (error) {
87 res.status(500).json({ success: false, error: (error as Error).message });
88 }
89});
90
91// Start server
92initDatabase().then(() => {
93 app.listen(3000, () => console.log('Server running on port 3000'));
94});Using with PostgreSQL
postgres-example.ts
1import 'reflect-metadata';
2import { Connection, Entity, Column, BaseModel, ConsoleLogger } from 'foundry-orm';
3
4@Entity('products')
5class Product extends BaseModel {
6 @Column('id')
7 id!: number;
8
9 @Column('name')
10 name!: string;
11
12 @Column('price')
13 price!: number;
14
15 @Column('stock')
16 stock!: number;
17}
18
19// Connect to PostgreSQL
20const connection = new Connection(
21 'postgres',
22 {
23 host: 'localhost',
24 port: 5432,
25 database: 'store',
26 user: 'postgres',
27 password: 'password',
28 maxConnections: 20 // Connection pool size
29 },
30 new ConsoleLogger()
31);
32
33await connection.connect();
34BaseModel.setConnection(connection);
35
36// CRUD operations
37const product = await Product.create({
38 name: 'Laptop',
39 price: 999.99,
40 stock: 50
41});
42
43const allProducts = await Product.findAll();
44console.log('Products:', allProducts);
45
46await connection.disconnect();Using with MongoDB
mongodb-example.ts
1import 'reflect-metadata';
2import { Connection, Entity, Column, BaseModel, ConsoleLogger } from 'foundry-orm';
3
4@Entity('orders')
5class Order extends BaseModel {
6 @Column('_id')
7 id!: string;
8
9 @Column('customer_id')
10 customerId!: string;
11
12 @Column('items')
13 items!: Array<{ product_id: string; quantity: number }>;
14
15 @Column('total')
16 total!: number;
17
18 @Column('status')
19 status!: string;
20}
21
22// Connect to MongoDB
23const connection = new Connection(
24 'mongodb',
25 {
26 url: 'mongodb://localhost:27017',
27 database: 'ecommerce',
28 maxPoolSize: 10
29 },
30 new ConsoleLogger()
31);
32
33await connection.connect();
34BaseModel.setConnection(connection);
35
36// Create order
37const order = await Order.create({
38 customerId: 'user_123',
39 items: [
40 { product_id: 'prod_1', quantity: 2 },
41 { product_id: 'prod_2', quantity: 1 }
42 ],
43 total: 299.97,
44 status: 'pending'
45});
46
47console.log('Order created:', order);
48
49await connection.disconnect();Using Transactions
transaction-example.ts
1import { Connection } from 'foundry-orm';
2
3const connection = new Connection('postgres', config);
4await connection.connect();
5
6// Perform transactional operations
7await connection.getAdapter().transaction(async (adapter) => {
8 // Deduct from account A
9 await adapter.query(
10 'UPDATE accounts SET balance = balance - $1 WHERE id = $2',
11 [100, accountA_id]
12 );
13
14 // Add to account B
15 await adapter.query(
16 'UPDATE accounts SET balance = balance + $1 WHERE id = $2',
17 [100, accountB_id]
18 );
19
20 // If any error occurs, transaction will be automatically rolled back
21});
22
23console.log('Transaction completed successfully');Using Query Builder
query-builder-example.ts
1import { QueryBuilder } from 'foundry-orm';
2
3const qb = new QueryBuilder('users', connection.getAdapter());
4
5// Build complex queries
6qb.where('age', '>', 18)
7 .where('status', '=', 'active')
8 .orderBy('created_at', 'DESC')
9 .limit(10)
10 .offset(0);
11
12const result = await qb.execute();
13console.log('Active adult users:', result.rows);Custom Logger
custom-logger.ts
1import { ILogger } from 'foundry-orm';
2
3class CustomLogger implements ILogger {
4 info(message: string, meta?: any): void {
5 console.info(`[${new Date().toISOString()}] INFO: ${message}`, meta);
6 }
7
8 error(message: string, meta?: any): void {
9 console.error(`[${new Date().toISOString()}] ERROR: ${message}`, meta);
10 // Send to error tracking service
11 }
12
13 debug(message: string, meta?: any): void {
14 if (process.env.NODE_ENV === 'development') {
15 console.debug(`[${new Date().toISOString()}] DEBUG: ${message}`, meta);
16 }
17 }
18}
19
20const connection = new Connection('postgres', config, new CustomLogger());More Examples
Check out our GitHub repository for more complete examples and sample applications.