Server middleware

The Amagaki server can be extended with Express middleware. This may be useful in a variety of scenarios, such as:

Remember, Amagaki is intended to be a static site generator. Request handlers made available on the server will not be available in production when serving a fully static site. Therefore, server middleware is most useful for adding functionality that enhances development velocity and the development workflow.

Examples

export default (pod: Pod) => {
    const serverPlugin = pod.plugins.get('ServerPlugin') as ServerPlugin;
 
<span class="hljs-comment">// Immediate example. Use for registering Express middleware.</span>
serverPlugin.<span class="hljs-title function_">register</span>(<span class="hljs-function"><span class="hljs-params">app</span> =&gt;</span> {
    app.<span class="hljs-title function_">use</span>(<span class="hljs-string">&#x27;/foo&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
        res.<span class="hljs-title function_">send</span>(<span class="hljs-string">&#x27;This is a response from custom middleware.&#x27;</span>);
    });
});

<span class="hljs-comment">// Async example. Use for running some task prior to server startup.</span>
serverPlugin.<span class="hljs-title function_">register</span>(<span class="hljs-title function_">async</span> () =&gt; {
    <span class="hljs-keyword">const</span> <span class="hljs-title function_">promise</span> = (<span class="hljs-params"></span>) =&gt; {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>&lt;<span class="hljs-built_in">void</span>&gt;(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> {
            <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
                <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;tested&#x27;</span>);
                <span class="hljs-title function_">resolve</span>();
            }, <span class="hljs-number">2000</span>);
        });
    };
    <span class="hljs-keyword">await</span> <span class="hljs-title function_">promise</span>();
});

}