Files
at-mintel/packages/next-utils/src/directus.ts
Marc Mintel 65fd248993
Some checks failed
Monorepo Pipeline / ⚡ Prioritize Release (push) Successful in 1s
Monorepo Pipeline / 🧹 Lint (push) Successful in 45s
Monorepo Pipeline / 🧪 Test (push) Successful in 54s
Monorepo Pipeline / 🏗️ Build (push) Failing after 1m46s
Monorepo Pipeline / 🚀 Release (push) Has been skipped
Monorepo Pipeline / 🐳 Build Directus (Base) (push) Has been skipped
Monorepo Pipeline / 🐳 Build Gatekeeper (Product) (push) Has been skipped
Monorepo Pipeline / 🐳 Build Build-Base (push) Has been skipped
Monorepo Pipeline / 🐳 Build Production Runtime (push) Has been skipped
chore(next-utils): fix generic propagation in createMintelDirectusClient and publish v1.7.12
2026-02-11 01:22:12 +01:00

73 lines
2.0 KiB
TypeScript

import {
createDirectus,
rest,
authentication,
DirectusClient,
RestClient,
AuthenticationClient,
} from "@directus/sdk";
export type MintelDirectusClient<Schema extends object = any> =
DirectusClient<Schema> & RestClient<Schema> & AuthenticationClient<Schema>;
/**
* Creates a Directus client configured with Mintel standards.
* Automatically handles internal vs. external URLs based on environment.
*/
export function createMintelDirectusClient<Schema extends object = any>(
url?: string,
): MintelDirectusClient<Schema> {
const isServer = typeof window === "undefined";
// 1. If an explicit URL is provided, use it.
if (url) {
return createDirectus<Schema>(url).with(rest()).with(authentication());
}
// 2. On server: Prioritize INTERNAL_DIRECTUS_URL, fallback to DIRECTUS_URL
if (isServer) {
const directusUrl =
process.env.INTERNAL_DIRECTUS_URL ||
process.env.DIRECTUS_URL ||
"http://localhost:8055";
return createDirectus<Schema>(directusUrl)
.with(rest())
.with(authentication());
}
// 3. In browser: Use a proxy path if we are on a different origin,
// or use the current origin if no DIRECTUS_URL is set.
const proxyPath = "/api/directus"; // Standard Mintel proxy path
const browserUrl =
typeof window !== "undefined"
? `${window.location.origin}${proxyPath}`
: proxyPath;
return createDirectus<Schema>(browserUrl).with(rest()).with(authentication());
}
/**
* Ensures the client is authenticated using either a static token or admin credentials
*/
export async function ensureDirectusAuthenticated(
client: MintelDirectusClient,
) {
const token = process.env.DIRECTUS_API_TOKEN || process.env.DIRECTUS_TOKEN;
const email = process.env.DIRECTUS_ADMIN_EMAIL;
const password = process.env.DIRECTUS_ADMIN_PASSWORD;
if (token) {
client.setToken(token);
return;
}
if (email && password) {
try {
await client.login({ email, password });
} catch (e) {
console.error("Failed to authenticate with Directus:", e);
throw e;
}
}
}