bigblocks
Version:
Complete Bitcoin UI component library - authentication, social, wallet, market, inscriptions, and blockchain interactions for React
128 lines (127 loc) • 4.96 kB
JavaScript
// BigBlocks Express Adapter
// Wraps the framework-agnostic core with Express/Node.js functionality
// Also works with Connect, Fastify, and other Node.js frameworks
import { createBigBlocksAuth, } from "../bigblocks-core.js";
/**
* Creates BigBlocks auth handlers for Express and Node.js frameworks
* Compatible with Express, Connect, Fastify, and others
*/
export function createExpressBigBlocks(options = {}) {
const core = createBigBlocksAuth(options);
// Express route handler
const handler = async (req, res) => {
try {
// Handle CORS if enabled
if (options.enableCORS) {
const origin = options.corsOptions?.origin || "*";
res.setHeader("Access-Control-Allow-Origin", Array.isArray(origin) ? origin.join(",") : origin);
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Auth-Token");
if (options.corsOptions?.credentials) {
res.setHeader("Access-Control-Allow-Credentials", "true");
}
// Handle preflight
if (req.method === "OPTIONS") {
res.status(200).end();
return;
}
}
// Convert Node.js req to standard Request
const url = new URL(req.url || "/", "http://localhost");
const body = req.method && ["POST", "PUT", "PATCH"].includes(req.method)
? JSON.stringify(req.body)
: null;
// Convert headers to Headers object
const headers = new globalThis.Headers();
for (const [key, value] of Object.entries(req.headers)) {
if (value) {
const headerValue = Array.isArray(value) ? value[0] : value;
if (headerValue) {
headers.set(key, headerValue);
}
}
}
const webRequest = new globalThis.Request(url.toString(), {
method: req.method || "GET",
headers,
body,
});
const response = await core.handler(webRequest);
const responseBody = await response.text();
// Set response status
res.status(response.status);
// Copy headers
response.headers.forEach((value, key) => {
res.setHeader(key, value);
});
// Send response
if (response.headers.get("content-type")?.includes("application/json")) {
res.json(JSON.parse(responseBody));
}
else {
res.send(responseBody);
}
}
catch (error) {
console.error("BigBlocks Express error:", error);
res.status(500).json({ error: "Internal server error" });
}
};
// Express middleware for authentication
const middleware = async (req, res, next) => {
try {
// Convert headers to Headers object
const headers = new globalThis.Headers();
for (const [key, value] of Object.entries(req.headers)) {
if (value) {
const headerValue = Array.isArray(value) ? value[0] : value;
if (headerValue) {
headers.set(key, headerValue);
}
}
}
const session = await core.api.getSession(headers);
if (!session) {
res.status(401).json({ error: "Unauthorized" });
return;
}
// Add user to request
req.user = session.user;
next();
}
catch (error) {
console.error("BigBlocks middleware error:", error);
res.status(500).json({ error: "Internal server error" });
}
};
// Router helper for mounting all auth routes
const router = (basePath = "/api/auth") => {
// This would be implemented based on the specific framework
// For Express: app.use(basePath, handler)
// For Fastify: fastify.register(handler, { prefix: basePath })
return {
path: basePath,
handler,
};
};
return {
// Main handler
handler,
// Middleware
middleware,
// Router helper
router,
// Direct API access
api: core.api,
// Config
options: core.options,
};
}
// Helper function to mount BigBlocks on Express app
export function mountBigBlocks(app, options) {
const bigblocks = createExpressBigBlocks(options);
const basePath = options?.basePath || "/api/auth";
// Mount the handler on the base path
app.use(basePath, bigblocks.handler);
return bigblocks;
}