Coder Social home page Coder Social logo

jaguar-dart / jaguar Goto Github PK

View Code? Open in Web Editor NEW
462.0 17.0 34.0 2.85 MB

Jaguar, a server framework built for speed, simplicity and extensible. ORM, Session, Authentication & Authorization, OAuth

Home Page: http://jaguar-dart.github.io

Dart 99.54% Shell 0.29% HTML 0.17%
jaguar dart web webserver rest-api rest restful websocket orm authentication authorization session http routing

jaguar's Introduction

Pub Build Status Gitter

Jaguar

Jaguar is a full-stack production ready HTTP server framework built to be fast, simple and intuitive.

Getting started

Familiar way to write routes

Jaguar class provides methods get, put, post, delete and options to quickly add route handlers for specific HTTP methods.

main() async {
  final server = Jaguar();  // Serves the API at localhost:8080 by default
  // Add a route handler for 'GET' method at path '/hello'
  server.get('/hello', (Context ctx) => 'Hello world!');
  await server.serve();
}

Powerful route matching

Easily define and access Path parameters

Path segments prefixed with : can match any value and are also captured as path variables. Path variables can be accessed using pathParams member of Context object.

main(List<String> args) async {
  final quotes = <String>[
    'But man is not made for defeat. A man can be destroyed but not defeated.',
    'When you reach the end of your rope, tie a knot in it and hang on.',
    'Learning never exhausts the mind.',
  ];

  final server = Jaguar();
  server.get('/api/quote/:index', (ctx) { // The magic!
    final int index = ctx.pathParams.getInt('index', 1);  // The magic!
    return quotes[index + 1];
  });
  await server.serve();
}
  • A path can have multiple path variables.
  • A path variable can appear at any position in the path.
  • A path variable can be matched against a Regular expression.
  • getInt, getDouble, getNum and getBool methods can be used to easily typecast path variables.
  • Using * as the final path segment captures/matches all following segments.

Easily access Query parameters

Query parameters can be accessed using queryParams member of Context object.

main(List<String> args) async {
  final quotes = <String>[
    'But man is not made for defeat. A man can be destroyed but not defeated.',
    'When you reach the end of your rope, tie a knot in it and hang on.',
    'Learning never exhausts the mind.',
  ];

  final server = Jaguar();
  server.get('/api/quote', (ctx) {
    final int index = ctx.queryParams.getInt('index', 1); // The magic!
    return quotes[index + 1];
  });
  await server.serve();
}

getInt, getDouble, getNum and getBool methods can be used to easily typecast query parameters into desired type.

One liner to access Forms

A single line is all it takes to obtain a form as a Map<String, String> using method bodyAsUrlEncodedForm on Request object.

main(List<String> arguments) async {
  final server = Jaguar(port: 8005);

  server.postJson('/api/add', (ctx) async {
      final Map<String, String> map = await ctx.req.bodyAsUrlEncodedForm(); // The magic!
      contacts.add(Contact.create(map));
      return contacts.map((ct) => ct.toMap).toList();
    });


  await server.serve();
}

One liner to serve static files

The method staticFiles adds static files to Jaguar server. The first argument determines the request Uri that much be matched and the second argument determines the directory from which the target files are fetched.

main() async {
  final server = Jaguar();
  server.staticFiles('/static/*', 'static'); // The magic!
  await server.serve();
}

JSON serialization with little effort

Decoding JSON requests can't be simpler than using one of the built-in bodyAsJson, bodyAsJsonMap or bodyAsJsonList methods on Request object.

Future<void> main(List<String> args) async {
  final server = Jaguar();
  server.postJson('/api/book', (Context ctx) async {
    // Decode request body as JSON Map
    final Map<String, dynamic> json = await ctx.req.bodyAsJsonMap();
    Book book = Book.fromMap(json);
    return book; // Automatically encodes Book to JSON
  });

  await server.serve();
}

Out-of-the-box Sessions support

main() async {
  final server = Jaguar();
  server.get('/api/add/:item', (ctx) async {
    final Session session = await ctx.req.session;
    final String newItem = ctx.pathParams.item;

    final List<String> items = (session['items'] ?? '').split(',');

    // Add item to shopping cart stored on session
    if (!items.contains(newItem)) {
      items.add(newItem);
      session['items'] = items.join(',');
    }

    return Response.redirect('/');
  });
  server.get('/api/remove/:item', (ctx) async {
    final Session session = await ctx.req.session;
    final String newItem = ctx.pathParams.item;

    final List<String> items = (session['items'] ?? '').split(',');

    // Remove item from shopping cart stored on session
    if (items.contains(newItem)) {
      items.remove(newItem);
      session['items'] = items.join(',');
    }

    return Response.redirect('/');
  });
  await server.serve();
}

jaguar's People

Contributors

kleak avatar lejard-h avatar lvscar avatar pin73 avatar rspilker avatar tejainece avatar tvolkert avatar xuexin 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

jaguar's Issues

Add the following to README

  • Organise route handlers in an API class
  • Session management
  • Authentication and Authorization
  • Mongo
  • SQL ORM

importing class and use it with Group result with no route

in api.dart

import "users.dart";

part 'api.g.dart';

@Api(path: 'api')
class ExampleApi extends Object with _$JaguarMedisApi {
  @Group(path: 'users')
  UsersGroup users = new UsersGroup();
}

in users.dart

class UsersGroup {
  @Route('/')
  String get() => "user";
}

default queryparam for num equal to num

@Get(path: '/ping')
String ping({num test: 1, int test1: 3, double test2: 4.0}) {
  return "pong $test $test1 $test2";
}

if you don't provide test in the query param test will be null instead of 1

Exception thrown only when multithread is active

Hi.

Today i was implementing he autogenerated beans and changed somo code and when you try to execute it ikt throws this exception.

Dumping native stack trace for thread 174d
  [0x00000000008dc1ca] dart::SnapshotReader::ProcessDeferredCanonicalizations()
  [0x00000000008dc1ca] dart::SnapshotReader::ProcessDeferredCanonicalizations()
  [0x00000000008dc594] dart::SnapshotReader::ReadObject()
  [0x0000000000745ff0] Unknown symbol
  [0x0000000000750581] Unknown symbol
  [0x00000000007713b4] dart::MessageHandlerTask::Run()
-- End of DumpStackTrace

This is the main

import 'package:jaguar/jaguar.dart' as jaguar;

import 'package:campusAPI/api.dart';

main(List<String> args) async {
  ExampleApi ea = new ExampleApi();

  jaguar.Configuration configuration =
      new jaguar.Configuration(multiThread: false,port:8756);
  configuration.addApi(ea);

  await jaguar.serve(configuration);
}

and this is the api part

library api;

import 'dart:async';
import 'dart:io';

import 'package:jaguar/jaguar.dart';
import 'package:jaguar/interceptors.dart';
import 'package:campusAPI/db/db.dart';

part 'api.g.dart';

@RouteGroup(path: '/media')
class ExampleRouteGroup extends _$JaguarExampleRouteGroup {
  ContenidoBean CB = new ContenidoBean(new PgAdapter('asdasdasdasdasda'));

  @Get()
  @WrapEncodeJsonableList()
  Future<List> mediaAll() => CB.findAll();

  @Get(path: '/:id', pathRegEx: const {'id': r'^[0-9]+$'})
  @WrapEncodeJsonableList()
  Future<List> mediaOne() => CB.findAll();
}

@Api(path: '/campus')
class ExampleApi extends _$JaguarExampleApi {
  @Group()
  final ExampleRouteGroup exampleRoutes = new ExampleRouteGroup();

  @Route(path: '/version', methods: const ['GET'])
  num version() => 0.1;
}

Json interceptor removes custom headers

Hi.
As talked on gitter when u use @WrapEncodeToJson() it removes the headers and the client dont know wath type of encode uses

Example code where it happens

@Get(
      headers: const {'Content-Language': 'es-ES','charset':'UTF-8'})
  @WrapPostgresDb(campusConnection)
  @WrapEncodeToJson()
  Future<List<Map>> getAll(@Input(PostgresDb) Connection db,
      {int offset: 0,
      int limit: 10,
      int formato,
      int evento,
      int plataforma,
      String aparece,
      int tema}) async {
    Adapter _adapter = new PgAdapter.FromConnection(db);
    bean = await new ContenidoBean(_adapter);
    Map parameters = {
      'formato': formato,
      'evento': evento,
      'plataforma': plataforma,
      'aparece': aparece,
      'tema': tema
    };
    return bean.findWithOptionals(limit, offset, parameters);
  }

Support for Nested interceptors

We need a way to fold multiple interceptors into one to save a lot of lines

@InterceptorClass()
class Auth extends Interceptor {
  void pre() {}

  void post() {}
}

@InterceptorClass()
class FetchLogedInUser extends Interceptor {
  void pre() {}

  void post() {}
}

//TODO somehow this should wrap Auth and FetchLogedInUser
@InterceptorClass()
class AuthAndFetchUser extends Interceptor {
  void pre() {}

  void post() {}
}

Websocket support

A way to upgrade Http connection to websocket and injecting the upgraded websocket to route.

Should this need @Websocket() annotation, instead of @Route()

Shelf integration

Integrate shelf into jaguar so that shelf handlers can be added to jaguar configuration and shelf middleware can be added to jaguar routes.

Video demos of Jaguar features

Create video demos to showcase jaguar features

  • Setting up Jaguar
  • Routes
  • Path variables input
  • Query parameters input
  • Header input
  • Cookie input
  • JSON encoding
  • JSON decoding
  • Session
  • Authetication and Authorization
  • JWT Authetication and Authorization
  • Serialization using jaguar_serializer
  • Using MongoDb
  • Using PostgreSql
  • Using MySQL
  • Writing Interceptors
  • Interceptor output
  • Multi-server configuration
  • Settings
  • Logging using scribe
  • Serving static files
  • Mustach template rendering
  • Facebook OAuth authentication
  • Github OAuth authentication
  • Google OAuth authentication
  • Twitter OAuth authentication
  • Using snapshot for deployment
  • Deploying using Nginx
  • Deploying using Apache

RegExp are not working

RegExp are not working because in the generated code they are missing inside the Route instanciation.

List<Route> _routes = <Route>[
  new Route(r"/:file", methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]),
];

should be:

List<Route> _routes = <Route>[
  new Route(r"/:file", methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], pathRegEx: {"file": "whatever here"}),
];

Finish basic documentation

Hi,

I liked the project and I am studying it as an alternative to redstone.
We need the documentation.
How do we mock a request?
How do we use session? Are variables zoned?
etc.

thanks

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.