Skip to content

Instantly share code, notes, and snippets.

@Wintereise
Created January 16, 2019 04:27
Show Gist options
  • Save Wintereise/3d59a0414419b4ecca5137c20fc29622 to your computer and use it in GitHub Desktop.
Save Wintereise/3d59a0414419b4ecca5137c20fc29622 to your computer and use it in GitHub Desktop.
TypeORM broken on aws-lambda runtime
import "reflect-metadata";
import { APIGatewayEvent, Context } from "aws-lambda";
import { BaseEntity, Column, Connection, Entity, getConnectionManager, PrimaryColumn } from "typeorm";
import v4 = require("uuid/v4");
@Entity()
export class TData extends BaseEntity {
@PrimaryColumn()
public id: string;
@Column()
public colA: string;
}
const manager = getConnectionManager();
let conn: Connection;
export async function handle(event: APIGatewayEvent, context: Context) {
if (manager.has("default")) {
conn = await manager.get("default");
console.log("Reusing EXISTING connection from manager.");
} else {
console.log("Creating NEW connection to DB.");
conn = await manager.create({
name: "default",
type: "postgres",
port: process.env.DB_PORT
? parseInt(process.env.DB_PORT, 10)
: 5432,
synchronize: true,
logging: "all",
host: process.env.DB_HOST,
username: process.env.DB_USERNAME,
database: process.env.DB_NAME,
password: process.env.DB_PASSWORD,
entities: [TData]
});
}
if (! conn.isConnected) {
console.log("CACHED connection was NOT connected, attempting to reconnect.")
await conn.connect();
}
const data = new TData();
data.id = v4();
data.colA = "colA";
await data.save();
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment