redstone-dart / redstone

A metadata driven microframework for Dart.
http://redstone-dart.github.io/redstone
MIT License
342 stars 42 forks source link

v0.6 Interceptor #141

Closed OzzieOrca closed 8 years ago

OzzieOrca commented 8 years ago

Below is my v0.5 code:

@web.Interceptor(r'/.*')
handleResponseHeader() {
  if (web.request.method == "OPTIONS") {
    //overwrite the current response and interrupt the chain.
    web.response = new shelf.Response.ok(null, headers: _createCorsHeader());
    web.chain.interrupt();
  } else {
    //process the chain and wrap the response
    web.chain.next(() => web.response.change(headers: _createCorsHeader()));
  }
}

_createCorsHeader() => {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept, Authorization"
};

It's been a little bit since I've tried upgrading to v0.6 (so the syntax might be slightly off) but I was unable to get the web.chain.next(...) to work right. I tried splitting it into 2 lines:

web.response.change(headers: _createCorsHeader());
web.chain.next();

If you could point me to some documentation an example that would be great. Thanks!

Pacane commented 8 years ago

Sure there you go!

import 'package:redstone/redstone.dart' as app;

@app.Group("/")
class Interceptors {
  @app.Interceptor(r'/.*')
  handleCORS() async {
    if (app.request.method != "OPTIONS") {
      await app.chain.next();
    }
    return app.response.change(headers: _createCorsHeader());
  }

  _createCorsHeader() => {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'PUT, GET, POST, OPTIONS, DELETE',
        'Access-Control-Allow-Headers':
            'Origin, X-Requested-With, Content-Type, Accept'
      };
}

The documentation for 0.6 is still not out though [I think]. There are some hidden snippets in the changelog file for the 0.6 branch. You can see the changes in the APIs as well.

Hope that helps.

If that solves your problem, please close this issue. Otherwise I'll close it if it becomes inactive.