Created
August 31, 2020 12:21
-
-
Save tigorlazuardi/cb57255e227bf157c8ed02b27562b75f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createConnection, Connection } from 'typeorm' | |
import User from 'some-folder' | |
import { Request, Response, NextFunction } from 'express' | |
// Infrastructure Codes | |
let readConn: Connection | |
let writeConn: Connection | |
// Contoh misal user repo | |
export async function dbRead() { | |
if (!readConn) { | |
readConn = await createConnection({ | |
type: 'mysql', | |
host: 'some-read-only-db-ip', // Target to Read-only database. It's always different IP | |
port: 3306, | |
username: 'test', | |
password: 'test', | |
database: 'test', | |
}) | |
} | |
return readConn.getRepository(User) | |
} | |
export async function dbWrite() { | |
if (!writeConn) { | |
writeConn = await createConnection({ | |
type: 'mysql', | |
host: 'some-write-only-db-ip', // Target to database with write access. It's always different IP from Read-Only | |
port: 3306, | |
username: 'test', | |
password: 'test', | |
database: 'test', | |
}) | |
} | |
return writeConn.getRepository(User) | |
} | |
// Endpoint Express JS (contoh) | |
app.post('/user', postUser) | |
app.get('/user', getUser) | |
// Controllers | |
async function getUser(req: Request, res: Response, next: NextFunction) { | |
const id = req.params.id | |
try { | |
const user = await getUser(Number(id)) | |
res.send(user) | |
} catch (err) { | |
res.send(err) | |
} | |
} | |
async function postUser(req: Request, res: Response, next: NextFunction) { | |
const { id, username } = req.body | |
try { | |
const user = await updateUsername(id, username) | |
res.send(user) | |
} catch (err) { | |
res.send(err) | |
} | |
} | |
// Repository Code | |
async function getUser(id: number): Promise<User> { | |
const db = await dbRead() | |
return await db.findOne(id) | |
} | |
async function updateUsername(id: number, username: string): Promise<User> { | |
const db = await dbWrite() | |
const user = new User() | |
user.name = username | |
await db.update(id, user) | |
// Don't use Read DB here. Most likely Master db has not sync yet to read db | |
const updatedUser = await db.findOne(id) | |
return updatedUser | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment