Search code examples
haxe

Use Static Middleware with Tink Web


I want to declare 2 routes. The first one, "/api" will provide some REST stuff, and the other one, "/static" should serve static content.

I tried to start from the quick start samples, but I don't know how to do this.

import tink.http.containers.*;
import tink.http.Response;
import tink.web.routing.*;

class Server {
    static function main() {
        var container = new NodeContainer(8080);
        var router = new Router<Root>(new Root());
        container.run(function(req) {
            return router.route(Context.ofRequest(req))
                .recover(OutgoingResponse.reportError);
        });
    }
}

class Root {
    public function new() {}

    @:get('/')
    @:get('/$name')
    public function hello(name = 'World')
        return 'Hello, $name!';
}

Solution

  • First of all, i had to use git version of tink_http_middleware and asys

    -lib tink_web
    -lib hxnodejs
    -lib tink_http_middleware:git:https://github.com/haxetink/tink_http_middleware.git
    -lib asys:git:https://github.com/benmerckx/asys.git
    -main server.Api
    -js www/api/api.js
    

    Next, @KevinResoL's answer was very helpful, i changed only one thing. staticMiddleware.apply(handler)

    package server;
    
    import tink.http.Handler;
    import tink.http.middleware.Static;
    import tink.http.containers.*;
    import tink.http.Response;
    import tink.web.routing.*;
    
    class Api {
        public static function main() {
    
            var container = new NodeContainer(8080);
            var router = new Router<ApiRoute>(new ApiRoute());
            var staticMiddleware = new Static("..","/");
            var handler:Handler = req -> router.route(Context.ofRequest(req)).recover(OutgoingResponse.reportError);
            container.run(staticMiddleware.apply(handler));
        }
    }
    
    class ApiRoute {
        public function new() { }
    
        @:sub public var api:Root = new Root();
    }
    
    class Root {
    
        public function new() { }
    
        @:get('/')
        @:get('/$name')
        public function serve(name = 'index.html')
            return 'Hello, $name!';
    }