Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 28x 28x 28x 28x 28x | import { Binding } from '@/core/bindings/Binding'
import { lazySettings } from '@/utils/lazySettings'
import { HyperdriveSettings } from '@/types/hyperdrive/HyperdriveSettings'
import type { HyperdriveCredentials } from '@/types/hyperdrive/HyperdriveCredentials'
import type { CloudflareEnv } from '@/types/CloudflareEnv'
/**
* Accessor for the Hyperdrive binding (`hyperdrive` in `wrangler.json`), which
* pools and caches connections to an external SQL database.
*
* @example
* ```ts
* const hyperdrive = new HyperdriveBinding() // binding name from the configuration layer
* const client = new Client({ connectionString: hyperdrive.connectionString(ctx.env) })
* ```
*
* @class
*
* @author Bayu Dwiyan Satria
* @version 1.0.0
* @since 1.0.0
*/
export class HyperdriveBinding<E extends CloudflareEnv = CloudflareEnv> extends Binding<Hyperdrive, E> {
/**
* Constructs a HyperdriveBinding instance.
*
* @param settings Resolved settings. Defaults to `resolve('hyperdrive')`, so callers
* normally construct this with no arguments at all.
*/
constructor(settings?: HyperdriveSettings) {
const settle = lazySettings<HyperdriveSettings>('hyperdrive', settings)
super(() => settle().binding)
}
/**
* Returns a connection string for the pooled database.
*
* @remarks
* The credentials in this string are scoped to the running Worker instance —
* never log it or hand it to a client.
*
* @param env The Worker environment.
* @returns A connection string accepted by the usual drivers and ORMs.
* @throws {@link MissingBindingError} When the Hyperdrive binding is absent.
*/
public connectionString(env: E): string {
return this.resolve(env).connectionString
}
/**
* Returns the connection details as discrete fields.
*
* Use this with drivers that take a credentials object rather than a URL.
*
* @param env The Worker environment.
* @returns The host, port, user, password, and database name.
*/
public credentials(env: E): HyperdriveCredentials {
const hyperdrive = this.resolve(env)
return {
host: hyperdrive.host,
port: hyperdrive.port,
user: hyperdrive.user,
password: hyperdrive.password,
database: hyperdrive.database
}
}
/**
* Opens a raw TCP socket to the database through Hyperdrive.
*
* The socket is unauthenticated — the driver is expected to authenticate
* using {@link HyperdriveBinding.credentials}.
*
* @param env The Worker environment.
* @returns The connected socket.
*/
public connect(env: E): Socket {
return this.resolve(env).connect()
}
}
|