middleware()

in fusion-plugin-introspect/src/server.js [67:106]


      middleware(deps) {
        // if the DI graph is resolvable, collect dep data again in case this plugin was registered too early
        data.server = [collectDependencyData(app)];

        // the data is the same in every browser session, so just collect once:
        // 1) if browser data has not been collected, write a <meta> tag in the HTML template
        // 2) if the browser detects the meta tag, it sends an XHR request with the browser data
        // 3) the server stores the browser data and sets a flag to store it
        // 4) subsequent requests no-op due to the flag being set
        const parse = parser();
        return async (ctx, next) => {
          if (!browserDataCollected) {
            if (ctx.element) {
              ctx.template.head.push(
                html`
                  <meta name="diagnostics" />
                `
              );
            }
            if (ctx.method === 'POST' && ctx.path.startsWith('/_diagnostics')) {
              ctx.status = 200;
              ctx.body = 'OK';
              // if requests happen in parallel, ensure only one triggers store call
              // by setting flag in same tick as flag check at the top of this middleware function
              browserDataCollected = true;
              // only then do async stuff
              await parse(ctx, async () => {});
              data.browser = [ctx.request.body]; // as array, to avoid schema break if we ever need to log per-browser graphs
              await store.store(data, deps);
            }
          } else if (
            ctx.method === 'POST' &&
            ctx.path.startsWith('/_diagnostics')
          ) {
            ctx.status = 200;
            ctx.body = 'OK';
          }
          return next();
        };
      },