typeorm#createConnection TypeScript Examples
The following examples show how to use
typeorm#createConnection.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: test-db-util.ts From barista with Apache License 2.0 | 7 votes |
private static async connection(name: string = 'default') {
const manager = getConnectionManager();
let dbConnection;
if (manager.has(name)) {
dbConnection = await manager.get(name);
} else {
dbConnection = await createConnection(name);
}
if (!dbConnection.isConnected) {
await dbConnection.connect();
}
return dbConnection;
}
Example #2
Source File: test-utils.ts From nestjs-starter-rest-api with MIT License | 7 votes |
resetDBBeforeTest = async (): Promise<void> => {
// This overwrites the DB_NAME used in the SharedModule's TypeORM init.
// All the tests will run against the e2e db due to this overwrite.
process.env.DB_NAME = TEST_DB_NAME;
console.log(`Dropping ${TEST_DB_NAME} database and recreating it`);
const connection = await createConnection({
name: TEST_DB_CONNECTION_NAME,
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'example',
});
await connection.query(`drop database if exists ${TEST_DB_NAME}`);
await connection.query(`create database ${TEST_DB_NAME}`);
await connection.close();
}
Example #3
Source File: index.ts From TypeScript-Login-Register with MIT License | 6 votes |
async function connectToDatabase() {
try {
await createConnection({
name: "lr",
type: "mariadb",
host: "localhost",
port: 3306,
username: "root",
password: "",
database: "lr",
synchronize: true,
logging: false,
entities: [Account, AccountValidation],
});
alt.log("Database connection successfull");
} catch (err) {
alt.log(err);
setTimeout(() => connectToDatabase(), 5000);
}
}
Example #4
Source File: index.ts From bluebubbles-server with Apache License 2.0 | 6 votes |
/**
* Creates a connection to the iMessage database
*/
async initialize() {
this.db = await createConnection({
name: "iMessage",
type: "better-sqlite3",
database: `${process.env.HOME}/Library/Messages/chat.db`,
entities: [Chat, Handle, Message, Attachment]
});
return this.db;
}
Example #5
Source File: helpers.ts From Cromwell with MIT License | 6 votes |
connectDatabase = async () => {
const connectionOptions: ConnectionOptions = {
type: "sqlite",
database: resolve(process.cwd(), 'db.sqlite3'),
entityPrefix: 'crw_',
synchronize: true,
entities: [
...ORMEntities,
]
}
await createConnection(connectionOptions);
}
Example #6
Source File: index.ts From nodeJS-express-postgresql with MIT License | 6 votes |
createConnection()
.then(_connection => {
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('dist'));
app.use('/user', userRoute.router);
app.use('/admin', adminData.router);
app.use(homeRouter);
app.use(errorRoute.error404);
app.listen(8080), console.log('Listening at 8080');
})
.catch(error => console.log(error));
Example #7
Source File: database.ts From jaebook-server with MIT License | 6 votes |
/**
* 데이터베이스 커넥션을 생성한다.
*/
export async function createDatabaseConnection(): Promise<void> {
try {
const connectionOpts: ConnectionOptions = {
type: "mysql",
host: env.database.host,
port: env.database.port,
username: env.database.usename,
password: env.database.password,
database: env.database.name,
synchronize: env.database.synchronize,
logging: env.database.logging,
entities: [__dirname + "/entities/*{.ts,.js}"],
};
useContainer(Container);
await createConnection(connectionOpts);
} catch (error) {
throw error;
}
}
Example #8
Source File: Migrate.ts From ADR-Gateway with MIT License | 6 votes |
connect = async (config:MigrationDbConfig, db?: Promise<Connection>) => {
const connectionPromise = db || (() => {
let options = _.merge(Version1EntityDefaults, config.Database);
return createConnection(options)
})()
return await connectionPromise;
}
Example #9
Source File: index.ts From adminjs-upload with MIT License | 6 votes |
run = async () => {
await createConnection()
const app = express()
app.use('/public', express.static('public'))
const admin = new AdminJS({
resources: [
createPhotoResource(),
createUserResource(),
createCustomResource(),
createPostResource(),
createMultiResource(),
],
version: { admin: true },
locale: {
language: 'en',
translations: {
labels: {
Photo: 'photos (Local)',
User: 'users (AWS)',
Custom: 'custom provider',
Post: 'posts (GCP)',
},
},
},
})
admin.watch()
const router = buildRouter(admin)
app.use(admin.options.rootPath, router)
app.listen(PORT, () => {
// eslint-disable-next-line no-console
console.log(`Example app listening at http://localhost:${PORT}`)
})
}
Example #10
Source File: alert-worker.ts From prism-frontend with MIT License | 6 votes |
async function run() {
const connection = await createConnection();
const alertRepository = connection.getRepository(Alert);
const alerts = await alertRepository.find();
console.info(`Processing ${alerts.length} alerts.`);
await Promise.all(
alerts.map(async (alert) => processAlert(alert, alertRepository)),
);
}
Example #11
Source File: db.ts From prox2 with GNU Affero General Public License v3.0 | 6 votes |
async function getConnection(): Promise<Connection> {
const connManager = getConnectionManager();
if (connManager.has("default")) {
await connManager.get().close();
}
return await createConnection({
type: "postgres",
url: postgres_url,
entities: [Confession],
synchronize: true,
logging: false,
});
}
Example #12
Source File: index.ts From aqualink-app with MIT License | 6 votes |
// Start a daily update for each sites.
exports.dailyUpdate = functions
.runWith({ timeoutSeconds: 540 })
.https.onRequest(async (req, res) => {
const dbUrl = functions.config().database.url;
process.env.SOFAR_API_TOKEN = functions.config().sofar_api.token;
// eslint-disable-next-line no-undef
const entities = dbEntities.map(extractEntityDefinition);
const conn = await createConnection({
...dbConfig,
url: dbUrl,
entities,
});
try {
await runDailyUpdate(conn);
res.json({ result: `Daily update on ${new Date()}` });
} catch (err) {
await sendErrorToSlack('dailyUpdate', err);
throw err;
} finally {
conn.close();
}
});
Example #13
Source File: test-setup.ts From typeorm-query-builder-wrapper with MIT License | 6 votes |
beforeAll(async () => {
connection = await createConnection({
type: 'postgres',
host: process.env.HOST,
port: 5432,
username: process.env.USERNAME,
password: process.env.PASSWORD,
database: process.env.DB,
schema: 'public',
entities: [path.join(__dirname, '../', '**/*.entity{.ts,.js}')],
migrationsRun: false,
logging: true,
logger: 'advanced-console',
maxQueryExecutionTime: 1000,
synchronize: false,
});
});
Example #14
Source File: createConn.ts From vsinder with Apache License 2.0 | 6 votes |
createConn = () =>
createConnection({
type: "postgres",
database: __prod__ ? undefined : "vsinder",
url: __prod__ ? process.env.DATABASE_URL : undefined,
entities: [join(__dirname, "./entities/*")],
migrations: [join(__dirname, "./migrations/*")],
// synchronize: !__prod__,
logging: !__prod__,
})
Example #15
Source File: addAdmin.ts From bouncecode-cms with GNU General Public License v3.0 | 6 votes |
(async function() {
const connection = await createConnection();
console.log(
await UserEntity.update(
{
email: args.email,
},
{
isAdmin: true,
},
),
);
await connection.close();
})();
Example #16
Source File: index.ts From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License | 6 votes |
createConnection(options)
.then(async (connection) => {
const app = express();
app.use(express.json({limit: '4mb'}));
app.use(express.urlencoded({limit: '4mb'}));
app.use(cors());
app.use(helmet());
app.use(morgan("short"));
app.use(express.json());
app.use("/", routes);
if (app.get("env") === "production") {
app.use(function (req, res, next) {
const protocol = req.get("x-forwarded-proto");
protocol == "https" ? next() : res.redirect("https://" + req.hostname + req.url);
});
}
await createOrIncrementClock(false);
const port = config.get("server.port");
app.get("/", function (req, res) {
res.send("Backend SDK is running");
});
const carekit_key = fs.readFileSync(__dirname + '/carekit-sdk.key');
const carekit_crt = fs.readFileSync(__dirname + '/carekit-sdk.crt');
https.createServer({
key: carekit_key, cert: carekit_crt,}, app)
.listen(port, function () {
console.log('CareKit Backend SDK is running!');
});
})
.catch((error) => console.log(error));
Example #17
Source File: connection.ts From crossfeed with Creative Commons Zero v1.0 Universal | 6 votes |
connectDb = async (logging?: boolean) => {
const connection = createConnection({
type: 'postgres',
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT ?? ''),
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
entities: [
Domain,
Service,
Vulnerability,
Scan,
Organization,
User,
Role,
ScanTask,
Webpage,
ApiKey,
SavedSearch,
OrganizationTag
],
synchronize: false,
name: 'default',
dropSchema: false,
logging: logging ?? false,
cache: true
});
return connection;
}
Example #18
Source File: scheduler.ts From backend with MIT License | 6 votes |
/// Returns the connection(pool) that should be used for all the jobs. The returned connection is always active, i.e. connected.
async function getActiveJobConnection() {
const release = await activeConnectionMutex.acquire(); //restrict access to this function to only one concurrent caller (to prevent creating two default connections, which occurs primarily if two jobs are scheduled at just the same time)
if (!jobConnection) {
logger.info("Create new connection to database...");
jobConnection = await createConnection();
} else if (!jobConnection.isConnected) {
logger.info("Job database connection is no longer connected. Reconnect...");
//Do this always, to have no transaction log that uses a connection that was closed (which then would result in errors)
invalidateActiveTransactionLog(); // that might not be necessary here, but include it for safety reasons
await jobConnection.connect();
}
release();
return jobConnection;
}
Example #19
Source File: ModelStore.ts From confidential-storage with Apache License 2.0 | 6 votes |
public static getConnection = async (url: string): Promise<Connection> => {
const connection = await createConnection({
// Typeorm does not allow two connections to have the same name
// So we use a different name everytime in order to have parallel connections
name: `${Date.now()}`,
type: 'mongodb',
useNewUrlParser: true,
useUnifiedTopology: true,
url,
entities: [Vault, VaultIndex, Document, Capability, Revocation, Chunk],
});
return connection;
};
Example #20
Source File: index.ts From mysql_node_angular with MIT License | 6 votes |
createConnection()
.then(async () => {
// create express app
const app = express();
// Middlewares
app.use(cors());
app.use(helmet());
app.use(express.json());
// Routes
app.use('/', routes);
// start express server
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
})
.catch(error => console.log(error));
Example #21
Source File: server.ts From opensaas with MIT License | 6 votes |
async function main() {
await createConnection();
const schema = await buildFederatedSchema({ resolvers: [RequestResolver] });
const context = ({ req }: Context) => {
return { tenantId: req.headers[TENANT_HEADER] || '' };
};
const server = new ApolloServer({ schema, context });
server.applyMiddleware({ app });
app.listen({ port: APP_PORT });
}
Example #22
Source File: db.ts From gear-js with GNU General Public License v3.0 | 6 votes |
async connect() {
this.connection = await createConnection({
type: 'postgres',
host: config.db.host,
port: config.db.port,
database: config.db.name,
username: config.db.user,
password: config.db.password,
entities: [TransferBalance],
synchronize: true,
});
this.repo = getRepository(TransferBalance);
log.info('Connected to database');
}
Example #23
Source File: index.ts From backend-postgres-typescript-node-express with MIT License | 6 votes |
export async function getConnection(): Promise<Connection> {
if (connection) {
return connection
}
connection = await createConnection()
return connection
}
Example #24
Source File: database.service.ts From rest-api.ts with MIT License | 6 votes |
public async getConnection(): Promise<Connection> {
if (DatabaseService.connection instanceof Connection) {
return DatabaseService.connection;
}
// const options = await getConnectionOptions(`orm_${new Date().getTime()}`);
try {
DatabaseService.connection = await createConnection();
this.logger.log('INFO', `Connection established`);
} catch (e) {
this.logger.log('ERROR', 'Cannot establish database connection');
process.exit(1);
}
return DatabaseService.connection;
}
Example #25
Source File: connection.spec.ts From advanced-node with GNU General Public License v3.0 | 6 votes |
jest.mock('typeorm', () => ({
Entity: jest.fn(),
PrimaryGeneratedColumn: jest.fn(),
Column: jest.fn(),
createConnection: jest.fn(),
getConnection: jest.fn(),
getConnectionManager: jest.fn(),
getRepository: jest.fn()
}))
Example #26
Source File: index.ts From type-graphql-dataloader with MIT License | 6 votes |
export function connect(logging: boolean = false) {
return createConnection({
type: "sqlite",
database: ":memory:",
entities: [path.resolve(__dirname, "entities", "*.{js,ts}")],
synchronize: true,
logging,
});
}
Example #27
Source File: typeormLoader.ts From spurtcommerce with BSD 3-Clause "New" or "Revised" License | 6 votes |
typeormLoader: MicroframeworkLoader = async (settings: MicroframeworkSettings | undefined) => {
const loadedConnectionOptions = await getConnectionOptions();
const connectionOptions = Object.assign(loadedConnectionOptions, {
type: env.db.type as any, // See createConnection options for valid types
host: env.db.host,
port: env.db.port,
username: env.db.username,
password: env.db.password,
database: env.db.database,
synchronize: env.db.synchronize,
logging: true,
logger: 'advanced-console',
entities: env.app.dirs.entities,
migrations: env.app.dirs.migrations,
});
const connection = await createConnection(connectionOptions);
await connection.runMigrations();
if (settings) {
settings.setData('connection', connection);
settings.onShutdown(() => connection.close());
}
}
Example #28
Source File: typeorm.spec.ts From ucast with Apache License 2.0 | 6 votes |
async function configureORM() {
class User {
id!: number
name!: string
projects!: Project[]
}
class Project {
id!: number
name!: string
user!: User
}
const UserSchema = new EntitySchema<User>({
name: 'User',
target: User,
columns: {
id: { primary: true, type: 'int', generated: true },
name: { type: 'varchar' },
},
relations: {
projects: {
target: 'Project',
type: 'one-to-many',
inverseSide: 'user'
}
}
})
const ProjectSchema = new EntitySchema<Project>({
name: 'Project',
target: Project,
columns: {
id: { primary: true, type: 'int', generated: true },
name: { type: 'varchar' },
},
relations: {
user: { target: 'User', type: 'many-to-one' }
}
})
const conn = await createConnection({
type: 'sqlite',
database: ':memory:',
entities: [UserSchema, ProjectSchema]
})
return { User, Project, conn }
}
Example #29
Source File: migrate.ts From squid with GNU General Public License v3.0 | 6 votes |
async run(): Promise<void> {
dotenv.config()
let cfg: ConnectionOptions = {
...createOrmConfig(),
subscribers: [],
synchronize: false,
migrationsRun: false,
dropSchema: false,
logging: ["query", "error", "schema"],
}
let connection = await createConnection(cfg)
try {
await connection.runMigrations({transaction: 'all'})
} finally {
await connection.close().catch(err => null)
}
}