From 698bc5b02a00418cb789b10d63cce86e2df756b2 Mon Sep 17 00:00:00 2001 From: jackwotherspoon Date: Wed, 25 Sep 2024 17:24:01 +0000 Subject: [PATCH] chore: refactor into private method --- src/sqladmin-fetcher.ts | 64 +++++++++++++++++++++++++---------------- 1 file changed, 39 insertions(+), 25 deletions(-) diff --git a/src/sqladmin-fetcher.ts b/src/sqladmin-fetcher.ts index 91a2e7de..394dc390 100644 --- a/src/sqladmin-fetcher.ts +++ b/src/sqladmin-fetcher.ts @@ -124,6 +124,40 @@ export class SQLAdminFetcher { } } + private parseIpAddresses( + ipResponse: sqladmin_v1beta4.Schema$IpMapping[] | undefined, + dnsName: string | null | undefined, + pscEnabled: boolean | null | undefined + ): IpAddresses { + const ipAddresses: IpAddresses = {}; + if (ipResponse) { + for (const ip of ipResponse) { + if (ip.type === 'PRIMARY' && ip.ipAddress) { + ipAddresses.public = ip.ipAddress; + } + if (ip.type === 'PRIVATE' && ip.ipAddress) { + ipAddresses.private = ip.ipAddress; + } + } + } + + // Resolve dnsName into IP address for PSC enabled instances. + // Note that we have to check for PSC enablement because CAS instances + // also set the dnsName field. + if (dnsName && pscEnabled) { + ipAddresses.psc = dnsName; + } + + if (!ipAddresses.public && !ipAddresses.private && !ipAddresses.psc) { + throw new CloudSQLConnectorError({ + message: 'Cannot connect to instance, it has no supported IP addresses', + code: 'ENOSQLADMINIPADDRESS', + }); + } + + return ipAddresses; + } + async getInstanceMetadata({ projectId, regionId, @@ -146,31 +180,11 @@ export class SQLAdminFetcher { }); } - const ipAddresses: IpAddresses = {}; - if (res.data.ipAddresses) { - for (const ip of res.data.ipAddresses) { - if (ip.type === 'PRIMARY' && ip.ipAddress) { - ipAddresses.public = ip.ipAddress; - } - if (ip.type === 'PRIVATE' && ip.ipAddress) { - ipAddresses.private = ip.ipAddress; - } - } - } - - // Resolve dnsName into IP address for PSC enabled instances. - // Note that we have to check for PSC enablement because CAS instances - // also set the dnsName field. - if (res.data.dnsName && res.data.pscEnabled) { - ipAddresses.psc = res.data.dnsName; - } - - if (!ipAddresses.public && !ipAddresses.private && !ipAddresses.psc) { - throw new CloudSQLConnectorError({ - message: 'Cannot connect to instance, it has no supported IP addresses', - code: 'ENOSQLADMINIPADDRESS', - }); - } + const ipAddresses = this.parseIpAddresses( + res.data.ipAddresses, + res.data.dnsName, + res.data.pscEnabled + ); const {serverCaCert} = res.data; if (!serverCaCert || !serverCaCert.cert || !serverCaCert.expirationTime) {