Skip to content

Instantly share code, notes, and snippets.

@mskoroglu
Created December 29, 2020 07:48
Show Gist options
  • Save mskoroglu/55b377d426a69940651091f0d9883b4d to your computer and use it in GitHub Desktop.
Save mskoroglu/55b377d426a69940651091f0d9883b4d to your computer and use it in GitHub Desktop.
Next.js with TypeORM - Database connection
import "reflect-metadata";
import {
Connection,
createConnection,
EntityTarget,
getConnectionManager,
Repository,
} from "typeorm";
import { Post } from "./posts/Post";
const CONNECTION_NAME = "default";
const CONNECTION_SLEEP_INTERVAL = 100;
const {
CONNECTION_HOST,
CONNECTION_PORT,
CONNECTION_USERNAME,
CONNECTION_PASSWORD,
CONNECTION_DATABASE,
} = process.env;
let connection: Connection;
let isConnecting = false;
async function initConnection() {
if (isConnecting) {
return;
}
isConnecting = true;
const connectionManager = getConnectionManager();
if (connectionManager.has(CONNECTION_NAME)) {
await connectionManager.get(CONNECTION_NAME).close();
console.warn(`Connection "${CONNECTION_NAME}" is closed.`);
}
connection = await createConnection({
name: CONNECTION_NAME,
type: "postgres",
host: CONNECTION_HOST,
port: parseInt(CONNECTION_PORT!, 10),
username: CONNECTION_USERNAME,
password: CONNECTION_PASSWORD,
database: CONNECTION_DATABASE,
entities: [Post],
synchronize: true,
logging: false,
});
isConnecting = false;
console.log(`Connection "${CONNECTION_NAME}" is initialized.`);
return connection;
}
async function getConnection() {
if (!connection?.isConnected) {
await initConnection();
while (!connection?.isConnected) {
await new Promise((resolve) =>
setTimeout(resolve, CONNECTION_SLEEP_INTERVAL)
);
}
}
return connection;
}
/**
* Example:
* export async function getAllPosts() {
* const postRepository = await getRepository(Post);
* return postRepository.find();
* }
*/
export async function getRepository<E>(entity: EntityTarget<E>) {
const connection = await getConnection();
return connection.getRepository(entity);
}
/**
* Example:
* export async function getPostBySlug(slug: string) {
* return withRepository(Post, (repository) =>
* repository.findOneOrFail({ where: { slug } })
* );
* }
*/
export async function withRepository<E, R>(
entity: EntityTarget<E>,
callback: (repository: Repository<E>) => R
) {
const repository = await getRepository(entity);
return callback(repository);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment