| 26 | } |
| 27 | |
| 28 | async connect(config) { |
| 29 | const connectionConfig = { |
| 30 | server: config.host, |
| 31 | authentication: { |
| 32 | type: 'default', |
| 33 | options: { |
| 34 | userName: config.username || undefined, |
| 35 | password: config.password || undefined |
| 36 | } |
| 37 | }, |
| 38 | options: { |
| 39 | port: parseInt(config.port, 10), |
| 40 | database: config.database, |
| 41 | trustServerCertificate: true |
| 42 | } |
| 43 | }; |
| 44 | |
| 45 | if (config.dialectOptions) { |
| 46 | // only set port if no instance name was provided |
| 47 | if ( |
| 48 | config.dialectOptions.options && |
| 49 | config.dialectOptions.options.instanceName |
| 50 | ) { |
| 51 | delete connectionConfig.options.port; |
| 52 | } |
| 53 | |
| 54 | if (config.dialectOptions.authentication) { |
| 55 | Object.assign(connectionConfig.authentication, config.dialectOptions.authentication); |
| 56 | } |
| 57 | |
| 58 | Object.assign(connectionConfig.options, config.dialectOptions.options); |
| 59 | } |
| 60 | |
| 61 | try { |
| 62 | return await new Promise((resolve, reject) => { |
| 63 | const connection = new this.lib.Connection(connectionConfig); |
| 64 | if (connection.state === connection.STATE.INITIALIZED) { |
| 65 | connection.connect(); |
| 66 | } |
| 67 | connection.queue = new AsyncQueue(); |
| 68 | connection.lib = this.lib; |
| 69 | |
| 70 | const connectHandler = error => { |
| 71 | connection.removeListener('end', endHandler); |
| 72 | connection.removeListener('error', errorHandler); |
| 73 | |
| 74 | if (error) return reject(error); |
| 75 | |
| 76 | debug('connection acquired'); |
| 77 | resolve(connection); |
| 78 | }; |
| 79 | |
| 80 | const endHandler = () => { |
| 81 | connection.removeListener('connect', connectHandler); |
| 82 | connection.removeListener('error', errorHandler); |
| 83 | reject(new Error('Connection was closed by remote server')); |
| 84 | }; |
| 85 | |