-
Notifications
You must be signed in to change notification settings - Fork 26
/
connect.ts
94 lines (80 loc) · 2.64 KB
/
connect.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import type { Adapter, ConnectionOptions } from "./adapters/adapter.ts";
import { joinPath } from "../deps.ts";
import { MysqlAdapter } from "./adapters/mysql.ts";
import { PostgresAdapter } from "./adapters/postgres.ts";
import { SqliteAdapter } from "./adapters/sqlite.ts";
import { BaseModel, ObjectType } from "./basemodel.ts";
export type DatabaseDialect = "mysql" | "postgres" | "sqlite";
interface ConnectionConfig extends ConnectionOptions {
type: DatabaseDialect;
models?: ObjectType<BaseModel>[];
}
/**
* Connect to database and automatically chose the driver
*/
export async function connect(): Promise<Adapter>;
/**
* Connect to database and automatically chose the driver
*
* @param options Connection options
*/
export async function connect(options: ConnectionConfig): Promise<Adapter>;
/**
* Connect to database and automatically chose the driver
*
* @param filePath Path to the database configuration file (default: "ormconfig.json")
*/
export async function connect(filePath: string): Promise<Adapter>;
/**
* Connect to database and automatically chose the driver
*
* @param options Connection options
*/
export async function connect(
options?: ConnectionConfig | string,
): Promise<Adapter> {
let adapter: Adapter;
let connectionOptions: ConnectionConfig;
// If connections options is not provided, look up for "ormconfig.json" file.
if (!options || typeof options === "string") {
try {
const path = joinPath(Deno.cwd(), options ? options : "./ormconfig.json");
const decoder = new TextDecoder("utf-8");
const result = decoder.decode(await Deno.readFile(path));
// TODO: validate connection options
connectionOptions = JSON.parse(result) as any;
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
throw new Error(
"Cannot connect to database without connection options!",
);
} else {
throw err;
}
}
} else {
connectionOptions = options;
}
switch (connectionOptions.type) {
case "mysql":
adapter = new MysqlAdapter(connectionOptions);
break;
case "postgres":
adapter = new PostgresAdapter(connectionOptions);
break;
case "sqlite":
adapter = new SqliteAdapter(connectionOptions);
break;
default:
throw new Error("Database type invalid!");
}
if (Array.isArray(connectionOptions.models)) {
for (let i = 0; i < connectionOptions.models.length; i++) {
if (connectionOptions.models[i].prototype instanceof BaseModel) {
(connectionOptions.models[i] as any).manager = adapter.getManager();
}
}
}
await adapter.connect();
return adapter;
}