Git Product home page Git Product logo

framework's Introduction

angel_framework

Pub build status

A high-powered HTTP server with support for dependency injection, sophisticated routing and more.

This is the core of the Angel framework. To build real-world applications, please see the homepage.

import 'package:angel_container/mirrors.dart';
import 'package:angel_framework/angel_framework.dart';

main() async {
    var app = Angel(reflector: MirrorsReflector());

    // Index route. Returns JSON.
    app.get('/', (req, res) => res.write('Welcome to Angel!'));
  
    // Accepts a URL like /greet/foo or /greet/bob.
    app.get(
      '/greet/:name',
      (req, res) {
        var name = req.params['name'];
        res
          ..write('Hello, $name!')
          ..close();
      },
    );
    
    // Pattern matching - only call this handler if the query value of `name` equals 'emoji'.
    app.get(
      '/greet',
      ioc((@Query('name', match: 'emoji') String name) => '๐Ÿ˜‡๐Ÿ”ฅ๐Ÿ”ฅ๐Ÿ”ฅ'),
    );
    
    // Handle any other query value of `name`.
    app.get(
      '/greet',
      ioc((@Query('name') String name) => 'Hello, $name!'),
    );
    
    // Simple fallback to throw a 404 on unknown paths.
    app.fallback((req, res) {
      throw AngelHttpException.notFound(
        message: 'Unknown path: "${req.uri.path}"',
      );
    });

    var http = AngelHttp(app);
    var server = await http.startServer('127.0.0.1', 3000);
    var url = 'http://${server.address.address}:${server.port}';
    print('Listening at $url');
    print('Visit these pages to see Angel in action:');
    print('* $url/greet/bob');
    print('* $url/greet/?name=emoji');
    print('* $url/greet/?name=jack');
    print('* $url/nonexistent_page');
}

framework's People

Contributors

axellebot avatar davidosborn avatar patoconnor43 avatar thosakwe avatar tvolkert 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

Watchers

 avatar  avatar  avatar  avatar  avatar

framework's Issues

More out of the box

  1. Angel routing API needs to kick butt (done)
  2. Client needs to kick butt (done)
  3. WebSockets need to kick butt
  4. Deployment needs to kick butt
  5. Passing params to services needs to kick butt (done)

ResponseContext@download sends wrong header

/// Sends a download as a response.
  download(File file, {String filename}) {
    header("Content-Disposition",
        'Content-Disposition: attachment; filename="${filename ?? file.path}"');
    header(HttpHeaders.CONTENT_TYPE, lookupMimeType(file.path));
    header(HttpHeaders.CONTENT_LENGTH, file.lengthSync().toString());
    responseData.add(file.readAsBytesSync());
  }

Content-Disposition header should start with "attachment", not "Content-Disposition"

Add a @Hooks annotation

@Hooks(const [myHook])
class MyService extends Service {
  @Hooks(const [auth.ownerOnly])
  modify(id, data, [params]) {}
}

This should be processed in the HookedService constructor.

Refactorings

This really should integrate with Nero at some point, things like req.io look better than 'underlyingRequest', etc.

Make startServer params optional, specify return type

Current:

startServer(InternetAddress address, int port) async {
  var server =
  await _serverGenerator(address ?? InternetAddress.LOOPBACK_IP_V4, port);
  this.httpServer = server;

  server.listen(handleRequest);

  return server;
}

Want:

Future<HttpServer> startServer([InternetAddress address, int port]);

Drop body_parser

Turns out the http_server package already has file upload support. I'm wondering, either drop my own body_parser, or somehow integrate theirs into mine.

Dependency Injection System

Having one of these would be very nice. The goal would be to make it only build a request handler once, so we wouldn't have to call dart:mirrors on every request.

Controllers already search req.properties for parameters, so we could just use this that way.

class RequestContext {
  void inject(String name, dependency) {
    properties[name] = dependency;  
  }
}

A base DependencyInjector class could be included in the framework. This is just a hyped-up middleware.

class DependencyInjector {
 /// Determines whether the given dependency should be automatically injected into the given request.
  Future<bool> shouldInject(RequestContext req) async => true;

  /// Load necessary resources
  Future inject(Angel app, RequestContext req, ResponseContext res) {}

  Future call(Angel app) async {
    app.before.add((RequestContext req, res) async {
      if (await shouldInject(req))
        await inject(app, req, res);
      return true;
    });
  }
}

For example, you can use this to easily create a singleton instance.

class SingletonInjector extends DependencyInjector {
  Map foo = {"bar": "baz"};

  @override
  inject(app, req, res) {
    req.inject("FOO", foo);
    return super.inject(app, req, res);
  }
}

@Expose("/news")
class MyController {

  @Expose("/:id")
  read(String id, Map FOO) async {
    // FOO auto-injected
    return "The news of the day is $FOO.";
  }
}

Route API Improvements

Should be able to cleanly execute a route, also maybe route.join or similar path-like functions. Might also extend from Pattern?

Rewrite Tests

  1. They are verbose
  2. They are ugly
  3. They are disorganized
  4. They do not test everything

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.