Coder Social home page Coder Social logo

redstone's Introduction

Redstone

DEPRECATED: This project is unmaintained for a long time, and is not compatible with Dart 2.x and newer.

Join the chat at https://gitter.im/redstone-dart/redstone Build Status

Redstone is an annotation driven web server micro-framework for Dart and influenced by Flask. It is based on shelf so you may also use any shelf middleware you like with Redstone.

Example

Redstone allows you to easily publish functions through a web interface, by just adding some annotations to them.

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

@web.Route("/")
helloWorld() => "Hello, World!";

main() {
  web.setupConsoleLog();
  web.start();
}

Installation

To install, set the redstone: "^0.6.4" constraint to your pubspec.

dependencies:
  redstone: "^0.6.4"

The following plugins are also available for this version:

redstone_mapper: 0.2.0-beta.1+1
redstone_mapper_mongo: 0.2.0-beta.1
redstone_mapper_pg: 0.2.0-beta.2+2
redstone_web_socket: 0.1.0-beta.1

Want to learn more?

Check out our wiki! :)

redstone's People

Contributors

astashov avatar austincummings avatar azenla avatar cgarciae avatar jodinathan avatar luizmineo avatar pacane avatar platelk avatar robertblackhart avatar sestegra avatar srawlins avatar stevemessick avatar stijnvanbael avatar vicb avatar y12studio avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

redstone's Issues

Example "Hello world" doesn't work.

Uncaught Error: Class '_LocalLibraryMirror' has no instance getter 'topLevelMembers'.

NoSuchMethodError: method not found: 'topLevelMembers'
Receiver: Instance of '_LocalLibraryMirror'
Arguments: []
Stack Trace:
#0 setUp (package:bloodless/server.dart:217:5)
#1 start. (package:bloodless/server.dart:158:10)
#2 Future.Future. (dart:async/future.dart:118)
#3 _createTimer. (dart:async-patch/timer_patch.dart:11)
#4 _handleTimeout (dart:io/timer_impl.dart:292)
#5 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:115)

Unhandled exception:
Class '_LocalLibraryMirror' has no instance getter 'topLevelMembers'.

NoSuchMethodError: method not found: 'topLevelMembers'
Receiver: Instance of '_LocalLibraryMirror'
Arguments: []
#0 _rootHandleUncaughtError.. (dart:async/zone.dart:700)
#1 _asyncRunCallbackLoop (dart:async/schedule_microtask.dart:23)
#2 _asyncRunCallback (dart:async/schedule_microtask.dart:32)
#3 _asyncRunCallback (dart:async/schedule_microtask.dart:36)
#4 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:119)

Customize the response status code

I have not found a way to customize easily the response status code, have I missed something ?

I would expect to be able to define it statically @app.Route('/', methods: const [app.POST], statusCode: HttpStatus.CREATED) or dynamically app.statusCode(HttpStatus.CREATED);.

Broken response with shelf

Hi,

I try to forward (like proxy) a response of http.get with shelf.Response. Unfortunatly this don't work always with static file like image (example:http://useoctobox.com/lib/images/logo.png)

  @_server.Route("/:website?", methods: const [_server.GET], matchSubPaths: true)
  Future<shelf.Response> wgetlike(String website){
      var completer = new Completer();

      http.get(website).then((clientResponse) {
        var response = new shelf.Response.ok(clientResponse.body, headers:{
          "content-type":clientResponse.headers["content-type"]
        });
        completer.complete(response);
      });
      return completer.future;
}

thanks for help!

About Dependency Injection

I read the docs on dependency injection but to me its still a mystery how to create the request from the client. Could you give me a small sample of how to use it?

EDIT:

Read about DI, so I see this question makes no sense. So now I ask, what is the benefit of using DI with in Redstone?

About JSON serialization

Sorry this is not an actual issue, but I see you serialize automatically serialize some responses to JSON. I've been searching a lot on how to serialize and haven't got any satisfactory answer.

Can you please tell me what method you use to serialize objects?

deployServer copies client side dependencies to bin

Hi!

I've just found bloodless recently. I really like the whole concept behind, thanks for developing it!

I have created a Grinder based build script following the example in the readme to test the build.
I've noticed that Grinder copies even client side dependencies to build/bin/packages, for example the browser package which is meaningless on the server side.
Client side dependencies are built as expected, bloddless doesn't gets copied to build/web/packages.

Better deps handling

The pubspec.yaml reads as follow

  di: ">=0.0.40 <2.0.0"
  stack_trace: ">=0.9.1 <2.0.0"

You can introduce a BC break by running a pub update because di and stack_trace can have a BC break. According to semver, the constraints should be:

  • `>=0.m.p <0.m+1.0' for pre 1.0 pkgs,
  • '>=M.m.p <M+1.0.0` for post 1.0

Crash with mapper transformer, OK without

I am writing the client side of my application. In it I am requesting from the server a list of Auctions which are being encoded like this:

@app.Route('/list', methods: const[app.POST])
@Encode()
Future<List<Auction>> getAuctions(@app.Body(app.JSON) Map parameters)
{
    String queryString = "select * from auctions";
    return postgreSql.query(queryString, Auction);
}

The Auction class looks like this (on both ends):

class Auction
{
    @Field()
    String item_name;

    @Field()
    int item_count;

    @Field()
    int total_cost;

    @Field()
    String username;

    @Field()
    DateTime start_time;

    @Field()
    DateTime end_time;
}

The client-side code looks like this:

import 'package:redstone_mapper/mapper.dart';
import 'package:redstone_mapper/mapper_factory.dart';
import 'dart:convert';
import 'dart:html';

void main()
{
    bootstrapMapper();

    HttpRequest.request('http://localhost:8181/ah/list',
            method: "POST", requestHeaders: {"content-type": "application/json"},
            sendData: JSON.encode({'username':{'operator':'=','value':'thad'}}))
        .then((HttpRequest req)
        {
                List<Auction> auctions = decode(JSON.decode(req.responseText),Auction);
                print(auctions);
        });
}

My pubspec.yaml file has the redstone_mapper transformer listed (as suggested):

name: ah_test
description: A sample web application
dependencies:
  browser: any
  redstone: any
  redstone_mapper: any
  intl: any
transformers:
- redstone_mapper

However, when running the client, it throws an exception:

Exception: Uncaught Error: MapperException:  Failed to decode: {item_name: Pick, item_count: 5, total_cost: 1000, username: thad, start_time: 2014-08-27T19:15:00.000, end_time: 2014-08-29T19:15:00.000} 
reason: Class 'String' has no instance method 'toIso8601String'.

NoSuchMethodError: method not found: 'toIso8601String'
Receiver: "2014-08-27T19:15:00.000"
Arguments: []
Stack Trace:
#0      _getOrCreateMapper.<anonymous closure> (package:redstone_mapper/mapper_factory_static.dart:220:13)
#1      _ListDecoder.call.<anonymous closure> (package:redstone_mapper/mapper_factory_static.dart:167:21)
#2      MappedListIterable.elementAt (dart:_internal/iterable.dart:397)
#3      ListIterator.moveNext (dart:_internal/iterable.dart:325)
#4      List.List.from (dart:core/list.dart:95)
#5      _ListDecoder.call (package:redstone_mapper/mapper_factory_static.dart:166:16)
#6      _getOrCreateMapper.<anonymous closure> (package:redstone_mapper/mapper_factory_static.dart:213:52)
#7      _TypeDecoder.convert (package:redstone_mapper/src/mapper_impl.dart:32:26)
#8      GenericTypeCodec.decode (package:redstone_mapper/mapper.dart:282:28)
#9      decode (package:redstone_mapper/mapper.dart:30:29)
#10     main.<anonymous closure> (http://localhost:8080/ah_test.dart:40:38)
#11     _RootZone.runUnary (dart:async/zone.dart:1082)
#12     _Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:488)
#13     _Future._propagateToListeners (dart:async/future_impl.dart:571)
#14     _Future._completeWithValue (dart:async/future_impl.dart:331)
#15     _Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:393)
#16     _asyncRunCallbackLoop (dart:async/schedule_microtask.dart:41)
#17     _asyncRunCallback (dart:async/schedule_microtask.dart:48)
#18     _handleMutation (dart:html:39006)

It looks like it's trying to parse the right thing, but it's failing to do the DateTime's correctly. The odd thing to me is that if I remove the redstone_mapper transformer, it runs without error and produces a correct result (I can manipulate the DateTime objects that are returned). Unfortunately, when compiling via pub build it does not run either way (with or without the transformer).

Am I doing something wrong with my code or is there a problem where the transformer is stripping out some class that is needed to decode the DateTime objects?

Can`t get ErrorHandler to be called

Hiya,

I was trying to set up an error handler and couldn't get it working. I'm not sure if it's my code or the library. Could you please have a look at my test case for which I'd expect the error handler to be called?

I'm on Dart 1.3 stable and the exact link I was testing is this:
http://localhost:8080/a/b

import 'dart:io';

import 'package:bloodless/server.dart' as app;

main() {
  app.setupConsoleLog();
  app.start();
}

@app.Group('/a')
class A {

  @app.ErrorHandler(HttpStatus.INTERNAL_SERVER_ERROR)
  handleInternalServerError() {
    print('Internal server error occured!');
  }

  @app.Route('/b')
  String defaultHandler() {
    print('Executing the default handler.');

    app.abort(HttpStatus.INTERNAL_SERVER_ERROR);

    return 'This is the default response.';
  }
}

Remove the pubspec.lock from git ?

This is a lib package, the pubspec.lock should not be versionned

.gitignore has

// Include when developing application packages
//pubspec.lock 

I think it should be uncommented, right ?

ORM Support

Hello,

coming from a Laravel background, I'd like to know, if there are any ORM plans?

Thanks and greets
ron

How to respond with an HTML

Is there an easy way to respond with an HTML file in the web folder? I most of the example I see respond json or plain text, but there must be an easy way to respond the start page.

Use the 'await' expression instead of callbacks in Redstone

The initial support for the 'await' expression in Dart has been commited, as you can read here:
https://code.google.com/p/dart/source/detail?r=39345
Using 'await' is a tremendous advantage for server side application development. Asynchronous programming becomes very easy to implement.
Can you consider to refactor Redstone to making use of it in a new branch, even if it will be released officially in Redstone only in a later version when the Dart team will complete it? I'm starting a new project using Redstone and I'd like to write from the beginning my code to make use of the 'async...await' pattern, to avoid having to rewrite most of my code. Thank you for this wonderful framework anyway!

Body as JSON Question

I'm not sure if I'm doing something wrong or I've stumbled into a bug.

Server-side, this works fine:

@app.Route("/user/login", methods: const [app.POST])
Map Login() {
  print("inside route.");
  return null;
}

Same thing, with a "body" request annotation fails:

@app.Route("/user/login", methods: const [app.POST])
Map Login( @app.Body(app.JSON) Map json) {
  print("inside route.");
  return null;
}

The error message I receive (client-side) is below. The server doesn't respond with any error at all.

Failed to load resource: the server responded with a status of 400 (Bad Request)
http://127.0.0.1:8080/user/login
Instance of '_XMLHttpRequestProgressEvent'

STACKTRACE:
null

This is my client-side code:

    var url = "http://127.0.0.1:8080/user/login";

    HttpRequest.request(url, method:'POST', sendData: JSON.encode(
        {"username" : "test",
         "password" : "ok" });

Can you please assist?

Thanks,
Greg

Log invalid requests

Redstone must generate log messages in the following scenarios:

  • method not allowed
  • content type not allowed
  • multipart request not allowed

Add support for routes where parameters contain slashes

I would like to have a route where everything past the base route would be included in the parameter, slashes and all. An example API might be:

@app.Route("/api/pages/:url", matchSubPaths: true)
pageData(String url){
    return url;
}

where a request such as GET: /api/pages/categoryName/pageName would match this route and return the response categoryName/pageName.

An example implementation of this in AngularDart is at dart-archive/route.dart#55

Different functions all HTTP-methods

I try to follow the principals here:
http://www.restapitutorial.com/lessons/httpmethods.html

Coming from PlayFramework (Java) and Jersey (Java) I really like the fact that you can have different functions for each HTTP-method.

Ideally, I'd like to have my users class to look like this:

@app.Group('/v1/users')
class UserController {

    //POST /v1/users.json - to create a new user
    @app.Route('.json', methods: const [app.POST]) 
    createUser() {
        //...
    }
    //GET /v1/users.json - to get the list of users
    @app.Route('.json', methods: const [app.GET]) 
    getUsers() {
        //...
    }
    //GET /v1/users/1.json - to get one user
    @app.Route('/:id.json', methods: const [app.GET]) 
    getUser(int id) {
        //...
    }
    //UPDATE /v1/users/1.json - to update user ID 1
    @app.Route('/:id.json', methods: const [app.UPDATE]) 
    updateUser(int id) {
        //...
    }
    //DELETE /v1/users/1.json - to delete user ID 1
    @app.Route('/:id.json', methods: const [app.DELETE]) 
    deleteUser(int id) {
        //...
    }

}

How would that be possible?
Let me know if I can help. I had a look at the competing Dart server frameworks and yours are the one closest how I think it should look. So again - Thanks :)

django style header/querparams

It would be awesome if you could make app.request.headers and app.request.queryParams work like django's which are actually set to an object of QueryDict.

Examples:
https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.QueryDict
https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.QueryDict

Here is an example:

@proxy
class QueryMap {
  Map _map;

  QueryMap(Map this._map);

  dynamic get(String key, [var defaultValue]) {
    if(this._map.containsKey(key)) {
      return this._map[key];
    } else if(defaultValue) {
      return defaultValue;
    } else {
      return null;
    }
  }
}

// This is how I implement it now:
Map queryParams = new QueryMap(app.request.queryParams);

queryParams.get('someParams', 'default value');

// but it would be nice if it was already set so we could do:
app.request.queryParams.get('someParams', 'default value');
// Or for backwards compatibility sake:
app.request.params.get('someParams', 'default value');
// And it just be an instance that used app.request.queryParams

I couldn't figure out darts equivalent to pythons getitem magic method so I omitted that.

This would honestly be useful for most of the maps in the request object and would make things much easier.

Improve documentation: serving static files

Currently, the documentation is not very clear about serving static files, since it's mentioned only in the shelf section. Examples can be added in the feature tour and routes sections.

Upgrade dependency on di to 2.0.1

Redstone is not using the most recent version of di which is causing problems when trying to include other libraries. Angular.dart now requires di: '>=2.0.1 <3.0.0' resulting in incompatible version constraints on di when trying to use both in the same project.

Mapper Documentation

I've been trying to get a simple mapper example working. On my server side, I have the following piece of code to handle posting a new auction to my database:

@app.Route('/ah/post', methods: const[app.POST])
Future addAuction(@Decode() Auction auction) => 
    postgreSql.execute("insert into auctions (item_name,total_cost,username) "
                       "values (@item_name, @total_cost, @username)",auction);

And there is an associated Auction class available:

class Auction
{
    @Field()
    String item_name;

    @Field()
    int total_cost;

    @Field()
    String username;
}

On my client side I have the following code:

void main()
{
    bootstrapMapper();

    Auction auction = new Auction()
        ..username = "thad2"
        ..item_name = "pick"
        ..total_cost = 500;
}

What is the correct way to post this object to the server so that it can be decoded and stored in the database? I'm unable to find any examples in the documentation of this step. I've tried using the http (client) library like this (after changing the total_cost to a string because it only allows Map<String,String>:

http.post("http://localhost:8181/ah/post", body:encode(auction)).then((response) => print(response.body));

But that will return a page with the error "form not supported for this handler". I've also tried to send it as a string by doing

http.post("http://localhost:8181/ah/post", body:JSON.encode(encode(auction))).then((response) => print(response.body));

But that will return a page with the error "string not supported for this handler".

Thanks for reading and sorry if I'm missing the obvious "do this" instruction.

Transformer problem with async/await

There appears to be an issue when using the client-side transformer and the main() method is declared as async. This is the (minimal) source code needed to produce a problem:

import 'package:redstone_mapper/mapper_factory.dart';

main() async
{
    bootstrapMapper();
}

And it produces this stack trace:

Exception: Uncaught Error: No top-level method 'bootstrapMapper' declared.

NoSuchMethodError: method not found: 'bootstrapMapper'
Receiver: top-level
Arguments: [...]
Stack Trace:
#0      NoSuchMethodError._throwNew (dart:core-patch/errors_patch.dart:173)
#1      main.<main_async_body> (http://localhost:8080/main.dart:7:2)
#2      Future.Future.<anonymous closure> (dart:async/future.dart:118)
#3      Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:12)
#4      _Timer._Timer.<anonymous closure> (dart:html:41761)

Removing the redstone_mapper from the transformers section of the pubspec.yaml file also removes this problem. I took a quick look at what the transformer was trying to do to see if there was something I could quickly fix, but I'm not smart enough to know how. Hopefully given this information a fix wouldn't be too hard for you to implement.

Groups - REST style

Thanks for this great framework. Just getting started using it.

This is a feature request.

I like the Jersey inspired groups annotation and I want to create a class that holds all the methods for a particular rest endpoint. But I cannot seem to get the following to work:

Collection: GET /users. (eg. json (/users.json)
One user: GET /users/1.

If I put @app.Group("/users") on the class, then Redstone does not let me use @app.Route(".json") on a method inside the class.

I try to follow these principals:
http://www.restapitutorial.com/lessons/httpmethods.html

Would that be possible?
Thanks again and kind regards
Anders Dam Kofoed

'XMLHttpRequest cannot load' error on HTTP Requests from Dart client to local Redstone server

I've lately been trying to build a Dart client that communicates with my Redstone server. If I run this url (localhost:8080/id/6192449487634432) on any browser I get back a JSON that I've set up, however, if a use

HttpRequest
    .getString ("http://localhost:8080/id/6192449487634432")
    .then (print);

on the Dart client, I get this weird error

XMLHttpRequest cannot load http://localhost:8080/id/6192449487634432. No 'Access-Control-Allow-Origin' 
header is present on the requested resource. Origin 'http://localhost:8081' is therefore not allowed access.

Is this a client or server issue? I've been told to modify the HttpResponse headers but since Redstone handles everything I don't know where to start.

Thanks a lot!

how to load the html file related to the route

Hi Luiz,
I liked your packages, but did not get how to use it.

I've 2 html files, index.html and details.html
in the index, there is field of userid, <a href="/details/:userid>

I understand the redstone will consider the route param, but how can I make it understand to load the details file as well..

hope my request is clear..
Can you provide example pls.

thank

Error : multiple call of shelf.Request.read()

Hi,

I have some issue on my project when i use interceptor with the parseRequestBody: true option.
When i activate the option i get the error :

Bad state: The 'read' method can only be called once on a shelf.Request/shelf.Response object.

this code produice the error

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

@app.Interceptor("/.*", parseRequestBody: true)
interceptorExample() {
app.chain.next();
}

@app.Route("/")
helloWorld() => "Hello, World!";

main() {
app.setupConsoleLog();
app.start();
}

Annotations for DI for Routes but not Interceptors?

Hi,

Trying to figure out why routes require an annotation for DI to work (@app.Inject), but Interceptors do not (at least in your example). Can you please explain?

This is from your documentation:

@app.Route('/service')
service(@app.Inject() ClassA objA) {
...
}
@app.Interceptor(r'/services/.+')
interceptor(ClassA objA, ClassB objB) {
...
}

Thanks,
Greg

Premature closure of a request with multiple futures

Consider the following Future:
Future<List> searchWord(String searchText) {
var completer = new Completer();
var sql = "select * from words where decorated like " +
"'" + searchText + "%' order by decorated";

connect(uri).then((conn){
  List<WordDto> words = new List<WordDto>();
  conn.query(sql).toList()
  .then((rows) {

    for(var row in rows){
      var word = new WordDto.create(row.pk.toString(), row.decorated, row.undecorated);
      words.add(word);
    }

  })
  .whenComplete(() {
    conn.close();
    completer.complete(words);
  });
});

return completer.future;

}

As soon as the connect(uri) future completes the request is closed. The framework does not seem to wait for the topmost future to complete before writing the response for target and then closing the request. Is there any way of getting around this. Thanks.

RAML plugin

Since redstone allows you to define APIs declaratively using methods, parameters, annotations, etc, it should be possible to generate a RAML doc from those.

Would the plugin API provide the necessary hooks to implement this?

Redstone running in the Editor vs Redstone running in Dartium

While trying to share code on both server and client, I ended up writing classes with a structure like this

class A
{
    @Field()
    C f = new C();
}

class B extends A
{
    @Field()
    D f = new D();
}

class C
{
    @Field()
    String s = "C";
}

class D extends C
{
    @Field()
    String s = "D";
}

where A and C are general version of some classes, B and D are browser or server specific. When I run this code by serving it via Run in Dartium

String s;
    print (s = encodeJson(new B()));
    print (decodeJson(s, B));

I get

{"f":{"s":"D"}}
Instance of 'B'

as expected. But when the index.html function is served by Redstone and executes the main function I get

{"f":{"s":"D"}}
Exception: MapperException: B#f: type 'C' is not a subtype of type 'D' of 'value'. 
package:redstone_mapper/mapper_factory.dart:358<anonymous closure> 
package:redstone_mapper/mapper_factory.dart:[email protected] 
package:redstone_mapper/src/mapper_impl.dart:32GenericTypeCodec.decode 
package:redstone_mapper/mapper.dart:321decodeJson 
package:redstone_mapper/mapper.dart:68main

It encodes correctly to JSON but fail to decode to a type B.

List support for @app.QueryParam

I've just tried this, and it doesn't work:

@app.Route("/id-test")
test(@app.QueryParam("id") List<String> ids) {
 return ids.join("+");
}

I'm calling it like:

/id-test?id=bla&id=32&id=124

Please support this argument variant.

I would like to have a CORS_headers that automatically adds, How can I do in the latest version (0.5.9) ??

The following code could not work in the current version, How can I set CORS-related Header
void addCorsHeaders(HttpHeaders headers) {
headers.add("Access-Control-Allow-Origin", "*, ");
headers.add("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
headers.add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
}

@app.Interceptor(r'/.*')
handleResponseHeader() {
addCorsHeaders(app.request.response.headers);
if (app.request.method == "OPTIONS") {
app.chain.interrupt();
} else {
app.chain.next();
}
}

Weird requests make redstone crash.

I have had a few different times where redstone crashed in a way I couldnt prevent and it was with weird requests. Here are some examples:

FINE: 2014-07-10 12:24:16.234: Received request for: http://www.daydaydata.com/proxy.txt
Uncaught Error: FormatException: Invalid port: ''
Stack Trace:
#0      Uri.parse (dart:core/uri.dart:315)
#1      _HttpRequest.requestedUri (dart:io/http_impl.dart:143)
#2      _fromHttpRequest (package:shelf/shelf_io.dart:107:46)
#3      handleRequest (package:shelf/shelf_io.dart:56:38)
#4      _process.<anonymous closure> (package:redstone/src/server_impl.dart:145:27)
#5      _rootRun (dart:async/zone.dart:723)
#6      _rootRun (dart:async/zone.dart:724)
#7      _rootRun (dart:async/zone.dart:724)
#8      _ZoneDelegate.run (dart:async/zone.dart:453)
#9      _CustomizedZone.run (dart:async/zone.dart:663)
#10     runZoned (dart:async/zone.dart:954)
#11     _process (package:redstone/src/server_impl.dart:143:11)
#12     _dispatchRequest (package:redstone/src/server_impl.dart:136:11)
#13     start.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:redstone/server.dart:409:25)
#14     _rootRunUnary (dart:async/zone.dart:730)
#15     _RootZone.runUnary (dart:async/zone.dart:864)
#16     _BaseZone.runUnaryGuarded (dart:async/zone.dart:582)
#17     _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:333)
#18     _BufferingStreamSubscription._add (dart:async/stream_impl.dart:263)
#19     _StreamController&&_SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:569)
#20     _StreamController._add (dart:async/stream_controller.dart:449)
#21     _StreamController.add (dart:async/stream_controller.dart:406)
#22     _HttpServer._handleRequest.<anonymous closure> (dart:io/http_impl.dart:2248)
#23     _createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:11)
#24     _handleTimeout (dart:io/timer_impl.dart:292)
#25     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:124)


Unhandled exception:
FormatException: Invalid port: ''
#0      _rootHandleUncaughtError.<anonymous closure>.<anonymous closure> (dart:async/zone.dart:713)
#1      _asyncRunCallbackLoop (dart:async/schedule_microtask.dart:23)
#2      _asyncRunCallback (dart:async/schedule_microtask.dart:32)
#3      _asyncRunCallback (dart:async/schedule_microtask.dart:36)
#4      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:128)

I don't know what http://www.daydaydata.com/proxy.txt is and its not the domain this service was running on so I think it was a bot.

I cant seem to find the log for the other error but it was something with the route. I will update this issue if it happens again.

I was going to try and contribute myself but I'm still not comfortable enough with dart or redstone to feel I know the better way to solve the issue. I thought maybe a try catch at the shelf_io.handleRequest call but I feel that maybe the httpRequest might should be validated before then because it could potentially cause issues in other places.

I'm not sure how to make the request in the way that it was done above to try and reliably reproduce it either.

Are HTTP sessions supported?

If I serve requests with the core HttpServer API, my browser will receive the session cookie (called 'DARTSESSID').

If I use bloodless to serve HTTP requests, the mentioned cookie isn't added to responses.
Is this because I meant to create only stateless web apps (or sessions implemented in a different way)?

Thanks,
Peter

Uncaught error: Illegal argument(s): scriptName and url cannot both be empty.

SEVERE: 2014-10-08 17:13:06.362: Uncaught error. Please, report this at https://github.com/luizmineo/redstone.dart - Illegal argument(s): scriptName and url cannot both be empty.

Stacktrace:

package:shelf/src/request.dart 157:7          Request.Request
package:shelf/shelf_io.dart 107:14            _fromHttpRequest
package:shelf/shelf_io.dart 56:38             handleRequest
package:redstone/src/server_impl.dart 162:27  _process.<fn>
dart:async                                    runZoned
package:redstone/src/server_impl.dart 160:11  _process
package:redstone/src/server_impl.dart 153:11  _dispatchRequest
package:redstone/server.dart 406:25           start.<fn>.<fn>.<fn>
dart:isolate                                  _RawReceivePortImpl._handleMessage

I received this error while my server was running, seems to still be up though. Let me know if I can provide any more details.

Error when Deploying with Grinder

I tried to follow the Deploy section on the wiki. I have the following setup:

  1. tool/grind.dart with the given code.
  2. grinder: any on pubspec
  3. I run pub run grinder:grind all on the command line

I get to following error message

grinder running [build] [deploy_server] [all]

[build]
  pub build
ProcessException: The system cannot find the file specified.

  Command: pub build
#0      _ProcessImpl._runAndWait (dart:io-patch/process_patch.dart:437)
#1      _runNonInteractiveProcessSync (dart:io-patch/process_patch.dart:586)
#2      Process.runSync (dart:io-patch/process_patch.dart:62)
#3      runProcess (package:grinder/grinder_tools.dart:77:41)
#4      build (package:grinder/grinder_tools.dart:188:15)
#5      GrinderTask.execute (package:grinder/grinder.dart:221:49)
#6      Grinder._executeTask (package:grinder/grinder.dart:359:30)
#7      Grinder.start.<anonymous closure> (package:grinder/grinder.dart:330:28)
#8      Future.forEach.<anonymous closure>.<anonymous closure> (dart:async/future.dart:310)
#9      Future.Future.sync (dart:async/future.dart:168)
#10     Future.forEach.<anonymous closure> (dart:async/future.dart:310)
#11     Future.Future.sync (dart:async/future.dart:168)
#12     Future.doWhile.<anonymous closure> (dart:async/future.dart:335)
#13     _RootZone.runUnaryGuarded (dart:async/zone.dart:1089)
#14     _RootZone.bindUnaryCallback.<anonymous closure> (dart:async/zone.dart:1118)
#15     Future.doWhile (dart:async/future.dart:341)
#16     Future.forEach (dart:async/future.dart:308)
#17     Grinder.start (package:grinder/grinder.dart:329:28)
#18     startGrinder (package:grinder/grinder.dart:95:32)
#19     main (file:///C:/Users/Cristian%20Garcia/Documents/Dart/redstonetest/restonetest/tool/grind.dart:9:17)
#20     _startIsolate (dart:isolate-patch/isolate_patch.dart:237)
#21     _startMainIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:192)
#22     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:130)

A quick side question: why doesn't pub build do the job on its own?

How can I Grabs the Origin request header ??

To allow access-control-allow-origin with multiple domains , I have to do the following things:
1.Grabs the Origin request header.
2.Checks if the origin value is one of the whitelisted values.
3.If it is valid, sets the Access-Control-Allow-Origin header with that value.

I don't know how I can Grabs the Origin request header in RedStone.dart ?

Multiple methods per path not working properly.

For some reason if you create multiple methods for the same route any parameters get set the first time a route is accessed then never update any time the path is changes when matching the route.

Here is an example:

@app.Group("/api")
class TestController {

  @app.Route('/:id')
  paramsTest(id) {
    return "GET $id";
  }

  @app.Route('/:id', methods: const [app.POST])
  paramsTestPost(id) {
    return "POST $id";
  }
}

The first time you go to /api/test it will return GET test and every time after. But if you change the route to /api/test2 then it will still output GET test not GET test2.

The problem doesn't seem to happen until you add more then one method to a certain path. So if you remove the paramsTestPost(id) method then paramsTest(id) will function correctly.

Redstone 0.5.18 method not found: 'isNotEmpty'

I upgraded to Dart 1.7 and Redstone 0.5.18 and am getting the following errors when running my Dart server. I'm not sure if this is something I'm doing wrong or if it is a bug but it worked fine on Redstone 0.5.16. I'd appreciate any suggestions you might have. Thanks!

SEVERE: 2014-10-15 23:21:09.135: Failed to configure handlers. - Closure call with mismatched arguments: function 'isNotEmpty'

NoSuchMethodError: method not found: 'isNotEmpty'
Receiver: Closure: () => List<String> from Function 'urlParameterNames':.
Arguments: []
Unhandled exception:
Uncaught Error: Closure call with mismatched arguments: function 'isNotEmpty'

NoSuchMethodError: method not found: 'isNotEmpty'
Receiver: Closure: () => List<String> from Function 'urlParameterNames':.
Arguments: []
Stack Trace:
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:45)
#1      _configureTarget (package:redstone/src/setup_impl.dart:834:60)
#2      _configureGroup.<anonymous closure>.<anonymous closure> (package:redstone/src/setup_impl.dart:512:25)
#3      Object&ListMixin.forEach (dart:collection/list.dart:60)
#4      _configureGroup.<anonymous closure> (package:redstone/src/setup_impl.dart:484:28)
#5      IterableBase.forEach (dart:collection/iterable.dart:227)
#6      _configureGroup (package:redstone/src/setup_impl.dart:482:39)
#7      _scanHandlers.<anonymous closure> (package:redstone/src/setup_impl.dart:386:20)
#8      List.forEach (dart:core-patch/growable_array.dart:254)
#9      _scanHandlers (package:redstone/src/setup_impl.dart:376:17)
#10     setUp (package:redstone/server.dart:464:18)
#11     start.<anonymous closure> (package:redstone/server.dart:396:10)
#12     Future.Future.<anonymous closure> (dart:async/future.dart:118)
#13     Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:12)
#14     _handleTimeout (dart:io/timer_impl.dart:292)
#15     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:130)

#0      _rootHandleUncaughtError.<anonymous closure> (dart:async/zone.dart:883)
#1      _asyncRunCallbackLoop (dart:async/schedule_microtask.dart:41)
#2      _asyncRunCallback (dart:async/schedule_microtask.dart:48)
#3      _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:84)
#4      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:131)

Mocking DI objects with redstone

Hi,

I'm trying to write my first unit test for my little project using Redstone, but am getting confused. My GET request takes a couple of objects that are injected at runtime:

/**
  * Verify is user is currently logged in or not (according to the server).
  */
@app.Route("/user/amiloggedin", methods: const [app.GET])
Map IsUserLoggedIn(@app.Inject() DataManager db, @app.Inject() SessionManager sessions) {
  logserver.log(Level.FINE, "[IsUserLoggedIn] Verify if user is logged in.");
     // ...
  }
}

Then when I try to mock this using your standard boilerplate (https://github.com/luizmineo/redstone.dart/wiki/Unit-test), I get the following error:

ERROR: hello service
Setup failed: Caught SetupException: [.Login] Invalid parameter: Can't inject db
package:redstone/server.dart 466:5 setUp
test_server.dart 13:21 main.
...

How do I mock-inject my "db" and "sessions" into the test class so this doesn't happen?

Thanks for your help,
Greg

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.