Skip to content

Commit 0e9a1f4

Browse files
Better detection of browser vs node environments
Parsing url in browser environment
1 parent b3440a4 commit 0e9a1f4

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

src/utilities.ts

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,14 @@
44

55
import { SQLiteCloudConfig, SQLiteCloudError, SQLiteCloudDataTypes } from './types'
66

7+
//
8+
// determining running environment, thanks to browser-or-node
9+
// https://www.npmjs.com/package/browser-or-node
10+
//
11+
12+
export const isBrowser: boolean = typeof window !== 'undefined' && typeof window.document !== 'undefined'
13+
export const isNode: boolean = typeof process !== 'undefined' && process.versions != null && process.versions.node != null
14+
715
//
816
// utility methods
917
//
@@ -107,26 +115,36 @@ export function popCallback<T extends ErrorCallback = ErrorCallback>(
107115
return { args: remaining }
108116
}
109117

110-
/** Parse connectionString like sqlitecloud://usernam:password@host:port/database?option1=xxx&option2=xxx into its components */
118+
/** Parse connectionString like sqlitecloud://username:password@host:port/database?option1=xxx&option2=xxx into its components */
111119
export function parseConnectionString(connectionString: string): SQLiteCloudConfig {
112120
try {
113121
// The URL constructor throws a TypeError if the URL is not valid.
114-
const url = new URL(connectionString)
115-
const database = url.pathname.replace('/', '') // pathname is database name, remove the leading slash
122+
// in spite of having the same structure as a regular url
123+
// protocol://username:password@host:port/database?option1=xxx&option2=xxx)
124+
// the sqlitecloud: protocol is not recognized by the URL constructor in browsers
125+
// so we need to replace it with https: to make it work
126+
const knownProtocolUrl = connectionString.replace('sqlitecloud:', 'https:')
127+
const url = new URL(knownProtocolUrl)
116128
const options: { [key: string]: string } = {}
117129

118130
url.searchParams.forEach((value, key) => {
119131
options[key] = value
120132
})
121133

122-
return {
134+
const config: SQLiteCloudConfig = {
123135
username: url.username,
124136
password: url.password,
125137
host: url.hostname,
126138
port: url.port ? parseInt(url.port) : undefined,
127-
database,
128139
...options
129140
}
141+
142+
const database = url.pathname.replace('/', '') // pathname is database name, remove the leading slash
143+
if (database) {
144+
config.database = database
145+
}
146+
147+
return config
130148
} catch (error) {
131149
throw new SQLiteCloudError(`Invalid connection string: ${connectionString}`)
132150
}

0 commit comments

Comments
 (0)