@nuxthub/core
Version:
Build full-stack Nuxt applications on Cloudflare, with zero configuration.
94 lines (93 loc) • 2.62 kB
JavaScript
import { ofetch } from "ofetch";
import { joinURL } from "ufo";
import { createError } from "h3";
import { requireNuxtHubFeature } from "../../../utils/features.js";
import { getCloudflareAccessHeaders } from "../../../utils/cloudflareAccess.js";
import { useRuntimeConfig } from "#imports";
let _db;
export function hubDatabase() {
requireNuxtHubFeature("database");
if (_db) {
return _db;
}
const hub = useRuntimeConfig().hub;
const binding = process.env.DB || globalThis.__env__?.DB || globalThis.DB;
if (hub.remote && hub.projectUrl && !binding) {
const cfAccessHeaders = getCloudflareAccessHeaders(hub.cloudflareAccess);
_db = proxyHubDatabase(hub.projectUrl, hub.projectSecretKey || hub.userToken, cfAccessHeaders);
return _db;
}
if (binding) {
_db = binding;
return _db;
}
throw createError("Missing Cloudflare DB binding (D1)");
}
export function proxyHubDatabase(projectUrl, secretKey, headers) {
requireNuxtHubFeature("database");
const d1API = ofetch.create({
baseURL: joinURL(projectUrl, "/api/_hub/database"),
method: "POST",
headers: {
Authorization: `Bearer ${secretKey}`,
...headers
}
});
return {
async exec(query) {
return d1API("/exec", {
body: { query }
}).catch(handleProxyError);
},
prepare(query) {
const stmt = {
_body: {
query,
params: []
},
bind(...params) {
return {
...stmt,
_body: { query, params }
};
},
async all() {
return d1API("/all", { body: this._body }).catch(handleProxyError);
},
async raw(options) {
return d1API("/raw", {
body: {
...this._body,
...options
}
}).catch(handleProxyError);
},
async run() {
return d1API("/run", { body: this._body }).catch(handleProxyError);
},
async first(colName) {
return d1API("/first", {
body: {
...this._body,
colName
}
}).catch(handleProxyError).then((res) => res || null);
}
};
return stmt;
},
batch(statements) {
return d1API("/batch", {
// @ts-expect-error _body is not recognized but internally used
body: statements.map((smtm) => smtm._body)
});
}
};
}
function handleProxyError(err) {
throw createError({
statusCode: err.statusCode,
// @ts-expect-error not aware of data property
message: err.data?.message || err.message
});
}