|
4 | 4 |
|
5 | 5 | import { SQLiteCloudConfig, SQLiteCloudError, SQLiteCloudDataTypes } from './types' |
6 | 6 |
|
| 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 | + |
7 | 15 | // |
8 | 16 | // utility methods |
9 | 17 | // |
@@ -107,26 +115,36 @@ export function popCallback<T extends ErrorCallback = ErrorCallback>( |
107 | 115 | return { args: remaining } |
108 | 116 | } |
109 | 117 |
|
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 */ |
111 | 119 | export function parseConnectionString(connectionString: string): SQLiteCloudConfig { |
112 | 120 | try { |
113 | 121 | // 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) |
116 | 128 | const options: { [key: string]: string } = {} |
117 | 129 |
|
118 | 130 | url.searchParams.forEach((value, key) => { |
119 | 131 | options[key] = value |
120 | 132 | }) |
121 | 133 |
|
122 | | - return { |
| 134 | + const config: SQLiteCloudConfig = { |
123 | 135 | username: url.username, |
124 | 136 | password: url.password, |
125 | 137 | host: url.hostname, |
126 | 138 | port: url.port ? parseInt(url.port) : undefined, |
127 | | - database, |
128 | 139 | ...options |
129 | 140 | } |
| 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 |
130 | 148 | } catch (error) { |
131 | 149 | throw new SQLiteCloudError(`Invalid connection string: ${connectionString}`) |
132 | 150 | } |
|
0 commit comments