|
| 1 | +import type { Federation } from "@fedify/fedify"; |
| 2 | +import type { |
| 3 | + NextFunction, |
| 4 | + Request as ERequest, |
| 5 | + Response as EResponse, |
| 6 | +} from "express"; |
| 7 | +import { Buffer } from "node:buffer"; |
| 8 | +import { Readable } from "node:stream"; |
| 9 | + |
| 10 | +type Middleware = (req: ERequest, res: EResponse, next: NextFunction) => void; |
| 11 | + |
| 12 | +export type ContextDataFactory<TContextData> = ( |
| 13 | + req: ERequest, |
| 14 | +) => TContextData | Promise<TContextData>; |
| 15 | + |
| 16 | +export function integrateFederation<TContextData>( |
| 17 | + federation: Federation<TContextData>, |
| 18 | + contextDataFactory: ContextDataFactory<TContextData>, |
| 19 | +): Middleware { |
| 20 | + return (req, res, next) => { |
| 21 | + const request = fromERequest(req); |
| 22 | + const contextData = contextDataFactory(req); |
| 23 | + const contextDataPromise = contextData instanceof Promise |
| 24 | + ? contextData |
| 25 | + : Promise.resolve(contextData); |
| 26 | + contextDataPromise.then(async (contextData) => { |
| 27 | + let notFound = false; |
| 28 | + let notAcceptable = false; |
| 29 | + const response = await federation.fetch(request, { |
| 30 | + contextData, |
| 31 | + onNotFound: () => { |
| 32 | + // If the `federation` object finds a request not responsible for it |
| 33 | + // (i.e., not a federation-related request), it will call the `next` |
| 34 | + // function provided by the Express framework to continue the request |
| 35 | + // handling by the Express: |
| 36 | + notFound = true; |
| 37 | + next(); |
| 38 | + return new Response("Not found", { status: 404 }); // unused |
| 39 | + }, |
| 40 | + onNotAcceptable: () => { |
| 41 | + // Similar to `onNotFound`, but slightly more tricky. |
| 42 | + // When the `federation` object finds a request not acceptable |
| 43 | + // type-wise (i.e., a user-agent doesn't want JSON-LD), it will call |
| 44 | + // the `next` function provided by the Express framework to continue |
| 45 | + // if any route is matched, and otherwise, it will return a 406 Not |
| 46 | + // Acceptable response: |
| 47 | + notAcceptable = true; |
| 48 | + next(); |
| 49 | + return new Response("Not acceptable", { |
| 50 | + status: 406, |
| 51 | + headers: { |
| 52 | + "Content-Type": "text/plain", |
| 53 | + Vary: "Accept", |
| 54 | + }, |
| 55 | + }); |
| 56 | + }, |
| 57 | + }); |
| 58 | + if (notFound || (notAcceptable && req.route != null)) return; |
| 59 | + await setEResponse(res, response); |
| 60 | + // Prevent the Express framework from sending the response again: |
| 61 | + res.end(); |
| 62 | + res.status = () => res; |
| 63 | + res.send = () => res; |
| 64 | + res.end = () => res; |
| 65 | + res.json = () => res; |
| 66 | + res.removeHeader = () => res; |
| 67 | + res.setHeader = () => res; |
| 68 | + }); |
| 69 | + }; |
| 70 | +} |
| 71 | + |
| 72 | +function fromERequest(req: ERequest): Request { |
| 73 | + const url = `${req.protocol}://${ |
| 74 | + req.header("Host") ?? req.hostname |
| 75 | + }${req.url}`; |
| 76 | + const headers = new Headers(); |
| 77 | + for (const [key, value] of Object.entries(req.headers)) { |
| 78 | + if (Array.isArray(value)) { |
| 79 | + for (const v of value) headers.append(key, v); |
| 80 | + } else if (typeof value === "string") { |
| 81 | + headers.append(key, value); |
| 82 | + } |
| 83 | + } |
| 84 | + return new Request(url, { |
| 85 | + method: req.method, |
| 86 | + headers, |
| 87 | + // @ts-ignore: duplex is not supported in Deno, but it is in Node.js |
| 88 | + duplex: "half", |
| 89 | + body: req.method === "GET" || req.method === "HEAD" |
| 90 | + ? undefined |
| 91 | + : (Readable.toWeb(req)), |
| 92 | + }); |
| 93 | +} |
| 94 | + |
| 95 | +function setEResponse(res: EResponse, response: Response): Promise<void> { |
| 96 | + res.status(response.status); |
| 97 | + response.headers.forEach((value, key) => res.setHeader(key, value)); |
| 98 | + if (response.body == null) return Promise.resolve(); |
| 99 | + const body = response.body; |
| 100 | + return new Promise((resolve) => { |
| 101 | + const reader = body.getReader(); |
| 102 | + reader.read().then(function read({ done, value }) { |
| 103 | + if (done) { |
| 104 | + reader.releaseLock(); |
| 105 | + resolve(); |
| 106 | + return; |
| 107 | + } |
| 108 | + res.write(Buffer.from(value)); |
| 109 | + reader.read().then(read); |
| 110 | + }); |
| 111 | + }); |
| 112 | +} |
0 commit comments