pneuma 0.6.1

  • Readme
  • Changelog
  • Example
  • Installing
  • 57

Pneuma pub package #

The vital spirit, soul, or creative force of a person.
"In Stoic philosophy, the pneuma penetrates all things, holding things together."
Wikipedia

Basically, yet another server framework, that provides middleware architecture and possibility to write MVC backend applications. Fast and very simple. Kickoff in a minute. If you used expressjs before then this framework will not be hard for you to understand.

Installation & setup #

Put dart_pneuma package into your pubspec.yaml dependencies section and run pub get. Import the dependency inside your main file

import 'package:pneuma/pneuma.dart';

void main() {
  Pneuma app = Pneuma();

  app.start();
}

This will start basic http server on default host and port 127.0.0.1:8080 You can either provide host and port named parametes into the constructor or use environment variables: IP and PORT

Usage #

Pneuma could be used in three ways:

  1. Writing routed handlers
  2. Using middlewares
  3. Writing controllers with route maps

Writing routed handlers

Idea is the same as in nodejs's expressjs library. You can just map paths to a specific handler which will process the request or pass it forward by calling next callback.

import 'package:pneuma/pneuma.dart';

final RegExp allRoutes = RegExp('.*');

void main() {
  Pneuma app = Pneuma()
    ..get('/user', (req, res, next) {
      res.send('Hello user');
    })
    .post('/user', (req, res, next) async {
      dynamic body = await req.body;
      
      print(body);
      res.send('User has been updated');
    })
    .match(allRoutes, (req, res, next) {
      res.send('Not found');
    });

  app.start();
}

Using middlewares

Middleware abstract class should be extended to create your middleware. You will need to override run method, which will receive Request and Response instances as an arguments and should return Future of null or next Middleware usually accessible with this.next property, as Middleware is LinkedListEntity

import 'package:pneuma/pneuma.dart';

class LogMiddleware extends Middleware {
  @override
  Future<Middleware> run(Request req, Response res) {
    DateTime start = DateTime.now();
    
    res.done.then((_res) {
      DateTime sent = DateTime.now();
      String stamp = sent.toIso8601String();
      double timeTaken = (sent.millisecondsSinceEpoch - start.millisecondsSinceEpoch) / 1000;

      print('[$stamp]: ${req.method.name} ${_res.statusCode} ${req.uri.toString()} took ${timeTaken} sec.');
    });

    return new Future.value(this.next);
  }
}

void main() {
  Pneuma app = Pneuma()
    ..use(LogMiddleware())
    ..get('/user', (req, res, next) {
      res.send('Hello user');
    });

  app.start();
}

Writing controllers with route map

As once popular and still widely used, MVC architectural pattern is very usefull to build large scale applications. Extended from Middleware, Controller class can also be extended to let you map application routes to specific action methods, which should process the request as an endpoints of the app.

class UserController extends Controller {
  @override
  get routeMap => {
    RegExp(r'^\/user'): {
      RequestMethod.GET: indexAction,
    },
  };

  void indexAction(Request req, Response res) {
    res.send('Index Page');
  }
}

void main() {
  Pneuma app = Pneuma()
    ..use(UserController());

  app.start();
}

Plans #

routeMap is a Map which, in oreder for actions to be mapped to specified paths, should be defined.

Next step for the controllers will be defining annotations to mark actions for a specific route in a more friendlier manner.

class UserController extends Controller {
  @Route(r'^\/user')
  void indexAction(Request req, Response res) {
    res.send('Index Page');
  }
}
# Changelog
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [0.6.1] - 2020-04-03
### Fixed
- Server status changes to `STOPPED` when `.stop` method called successfuly
### Updated
- Updated types, removed few files

## [0.6.0] - 2020-04-03
### Added
- Added `Request` and `Response` to `beforeAction` and `afterAction`
### Changed
- Rewritten `routeMap` function type to ActionHandler making params as an optional `List<String>` for better typing

## [0.5.1] - 2020-04-02
### Added
- Added `beforeAction` and `afterAction` to the `Controller`

## [0.5.0] - 2020-03-31
### Updated
- Linted and updated code

## [0.4.0] - 2019-03-20
### Added
- Added baseUrl parameter for handling base of middleware

## [0.3.4] - 2019-03-04
### Fixed
- Dart native response close handling. Was getting error on trying to process thrown exception

## [0.3.3] - 2019-03-03
### Updated
- Access additional parameters via [] operator

### Fixed
- Content type of type string

## [0.3.2] - 2019-03-03
### Added
- Store additional parameters for request in Map `req.additionalParams`

## [0.3.1] - 2019-03-03
### Added
- ip to Request from connectionInfo

## [0.3.0] - 2018-08-17
### Changed
- Pneuma server get/post/etc shortcut methods accepts dynamic as handler. Could be middleware
- Controller now passes matched params as an arguments aside of req, and res

## [0.2.5] - 2018-08-15
### Added
- Response timeout added

### Fixed
- Adding default headers before app start
- Controller routes fixed

## [0.2.4] - 2018-08-15
### Added
- Added ServerStatus to Pneuma
- On start and server error handling
- ServerStatus stream

### Changed
- Updated HttpHeaders to dart 2 for Response

## [0.2.2] - 2018-08-14
### Added
- request headers

## [0.2.1] - 2018-08-14
### Added
- `stop` for Pneuma instance to stop HttpServer
- methods to controll HttpServer#defaultHeaders

## [0.2.0] - 2018-08-14
### Changed
- Updated to dart version 2

## [0.1.0] - 2018-08-06
### Added
- Middleware as an interface
- Controller to work in MVC kind of manner
- example dir with example

### Changed
- Future based middleware chain

### Removed
- Custom events class
- waterfall recurcive middleware handling
- Log to be a separate middleware

## [0.0.3] - 2015-08-16
### Added
- Initial structure
- Event based controllers concept
- MiddlewareHandler through a waterfall recurcive stack

example/example.dart

import 'dart:async';
import 'package:pneuma/pneuma.dart';

class LogMiddleware extends Middleware {
  @override
  Future<Middleware> run(Request req, Response res, {String baseUrl = '/'}) {
    DateTime start = DateTime.now();

    res.done.then((_res) {
      DateTime sent = DateTime.now();
      String stamp = sent.toIso8601String();
      double timeTaken =
          (sent.millisecondsSinceEpoch - start.millisecondsSinceEpoch) / 1000;

      print(
          '[$stamp]: ${req.method.name} ${_res.statusCode} ${req.uri.toString()} took ${timeTaken} sec.');
    });

    return Future.value(this.next);
  }
}

class CustomMiddleware extends Middleware {
  @override
  Future<Middleware> run(Request req, Response res,
      {String baseUrl = '/'}) async {
    if (req.path == '/test') {
      await Future.delayed(Duration(seconds: 1));

      return this.next;
    } else if (req.path == '/error') {
      throw Exception('CustomError');
    } else if (req.path == '/timeout') {
      return Future.delayed(Duration(seconds: 10));
    }

    return this.next;
  }
}

class TestController extends Controller {
  @override
  get routeMap => {
        RegExp(r'^\/controller\/timeout$'): {
          RequestMethod.GET: timeoutAction,
        },
        RegExp(r'^\/controller\/error$'): {
          RequestMethod.GET: errorAction,
        },
        RegExp(r'^\/controller\/params\/(\d+)\/(.+)$'): {
          RequestMethod.GET: paramsAction,
        },
        RegExp(r'^\/controller'): {
          RequestMethod.GET: indexAction,
        }
      };

  Future<bool> beforeAction(ActionHandler action, Request req, Response res) async {
    if (action == indexAction) {
      // E.g. check authorization etc
      res.status(403).send('Unauthorized');

      // after returning false, original action and `afterAction` will not be called
      return false;
    }

    return true;
  }

  void afterAction(Request req, Response res) {
    print('That was ${req.uri.toString()} with status ${res.statusCode}');
  }

  Future indexAction(Request req, Response res) async {
    res.send('Index Page');
  }

  Future paramsAction(Request req, Response res, List<String> matches) async {
    res.send('Index: ${matches[0]}, and ${matches[1]}');
  }

  Future timeoutAction(Request req, Response res) async {
    await Future.delayed(Duration(seconds: 10));
  }

  Future errorAction(Request req, Response res) {
    throw Exception('Oops controller');
  }
}

main() async {
  Pneuma srv = Pneuma(port: 8080);

  srv
    ..use(LogMiddleware())
    ..use(CustomMiddleware())
    ..use(TestController())
    ..get('/new', (Request req, Response res, next) {
      res.send('Welcome');
    })
    ..post('/new', (Request req, Response res, next) {
      req.body.then((data) {
        print(data.body);
        res.send('Welcome post');
      });
    });

  await srv.start();
  print('Server started at ${srv.host}:${srv.port}');
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  pneuma: ^0.6.1

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:pneuma/pneuma.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
16
Health:
Code health derived from static analysis. [more]
98
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
57
Learn more about scoring.

We analyzed this package on Apr 3, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.6

Health issues and suggestions

Document public APIs. (-0.50 points)

116 out of 118 API elements have no dartdoc comment.Providing good documentation for libraries, classes, functions, and other API elements improves code readability and helps developers find and use your API.

Fix lib/src/app.dart. (-1.99 points)

Analysis of lib/src/app.dart reported 4 hints:

line 86 col 7: Use rethrow to rethrow a caught exception.

line 108 col 7: Use rethrow to rethrow a caught exception.

line 145 col 5: Future results in async function bodies must be awaited or marked unawaited using package:pedantic.

line 166 col 7: Future results in async function bodies must be awaited or marked unawaited using package:pedantic.

Format lib/src/controller.dart.

Run dartfmt to format lib/src/controller.dart.

Format lib/src/types.dart.

Run dartfmt to format lib/src/types.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.6.1 <3.0.0
http_server >=0.9.8 <1.0.0 0.9.8+3
Transitive dependencies
mime 0.9.6+3
path 1.6.4
Dev dependencies
test >=1.12.0 <1.13.0