@nuxthub/core
Version:
Build full-stack Nuxt applications on Cloudflare, with zero configuration.
68 lines (67 loc) • 2.4 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";
const _vectorize = {};
export function hubVectorize(index) {
requireNuxtHubFeature("vectorize");
if (_vectorize[index]) {
return _vectorize[index];
}
const hub = useRuntimeConfig().hub;
const bindingName = `VECTORIZE_${index.toUpperCase()}`;
const binding = process.env[bindingName] || globalThis.__env__?.[bindingName] || globalThis[bindingName];
if (hub.remote && hub.projectUrl && !binding) {
const cfAccessHeaders = getCloudflareAccessHeaders(hub.cloudflareAccess);
_vectorize[index] = proxyHubVectorize(index, hub.projectUrl, hub.projectSecretKey || hub.userToken, cfAccessHeaders);
return _vectorize[index];
}
if (binding) {
_vectorize[index] = binding;
return _vectorize[index];
}
if (import.meta.dev && !hub.remote) {
return void 0;
}
throw createError(`Missing Cloudflare Vectorize binding (${bindingName})`);
}
export function proxyHubVectorize(index, projectUrl, secretKey, headers) {
requireNuxtHubFeature("vectorize");
const vectorizeAPI = ofetch.create({
baseURL: joinURL(projectUrl, `/api/_hub/vectorize/${index}`),
method: "POST",
headers: {
Authorization: `Bearer ${secretKey}`,
...headers
}
});
return {
async insert(vectors) {
return vectorizeAPI("/insert", { body: { vectors } }).catch(handleProxyError);
},
async upsert(vectors) {
return vectorizeAPI("/upsert", { body: { vectors } }).catch(handleProxyError);
},
async query(query, params) {
return vectorizeAPI("/query", { body: { query, params } }).catch(handleProxyError);
},
async getByIds(ids) {
return vectorizeAPI("/getByIds", { body: { ids } }).catch(handleProxyError);
},
async deleteByIds(ids) {
return vectorizeAPI("/deleteByIds", { body: { ids } }).catch(handleProxyError);
},
async describe() {
return vectorizeAPI("/describe").catch(handleProxyError);
}
};
}
function handleProxyError(err) {
throw createError({
statusCode: err.statusCode,
// @ts-expect-error not aware of data property
message: err.data?.message || err.message
});
}