0.1.30 • Published 6 years ago

exort v0.1.30

Weekly downloads
3
License
ISC
Repository
github
Last release
6 years ago

Exort Framework

Contents

1. Overview

Exort is a framework composed of popular libraries: ExpressJS, TypeORM, ReactJS and TypeScript. This framework implies MVC style with services. Each model has its own service to be used by the controller to communicate with models.

2. Requirements

  • Unix environment
  • Use Visual studio code ( optional but recommended to have intellisense support )

3. Installation

Download the structure here: https://github.com/exort-team/exort-structure Follow the following:

cd path/to/project
npm install
npm run build
npm start

4. Folder structure

  • public
  • src
    • client
    • server
      • config
        • app.ts
          • contains app configuration like timezone, environment and port. Custom configuration can be put here.
        • assets.ts
          • if the app will also server the static files you can configure the paths and prefixes.
        • db.ts
          • database configuration. You can have multiple database configuration and set the default.
        • index.ts
        • logger.ts
          • configure what to show on stdout of app
        • request.ts
          • configure encoding and max size of request.
        • router.ts
          • since exort framework runs on top of expressjs you can still configure expressjs router thru this
        • session.ts
          • session configuration
        • socketio.ts
          • exort uses socketio. This file lets you configure socketio
        • view.ts
          • exort uses nunjucks templating engine. This file lets you configure nunjucks.
      • console
        • commands
          • contains console Command classes.
        • Bootstrap.ts
        • routes.ts
        • schedules.ts
      • database
        • migrations
          • contains database migration files generated by node cli migration:make
        • seeds
          • contains database seeder files
      • events
      • http
        • controllers
          • contains the HTTP controllers. Filenames should be the same with the class name.
        • middleware
          • contains the middleware classes. Filenames should be the same with the class name.
        • Bootstrap.ts
        • routes.ts
          • contains the routing of controllers.
        • ErrorHandler.ts
      • lang
        • en
          • contains english translations
      • models
        • contains the database models
      • services
      • tests
      • cli.ts
      • start.ts
      • tsconfig.json
    • styles
  • views
    • this contains the html templates to be rendered by the controller

5. HTTP Controller and Routing

Below is an example of a controller.

src/server/http/controllers/HomeController.ts

import { HttpController } from 'exort/web';

export class HomeController extends HttpController {

  public async index() {
    this.response.render('index', { name: 'exort' });
  }
}

Always remember that when creating a controller the filename should match the class name just like the above example. This controller only render views/index.html template.

views/index.html

<html>
  <head>
    <title>Hello world</title>
  </head>
  <body>
    Hello {{ name }}
  </body>
</html>

The template above is only displaying the name data passed by HomeController.

For the controller to work we need to route it by editing src/server/http/routes.ts

src/server/http/routes.ts

import { Application } from 'exort/core';
import { Router } from 'exort/web';

/**
 * Setup routes
 */
export function setup(router: Router, app: Application): void {
  router.get('/', 'HomeController@index');
}

The line router.get('/', 'HomeController@index'); assigns a route for HomeController.

6. Model and Services

You can't use a model directly in a controller you must use a service for the model to communicate with controller.

Create a model inside src/server/models.

src/server/models/User.ts

import { Column, Entity, Model, PrimaryGeneratedColumn, CreateDateColumn } from 'exort/db';

@Entity('users')
export class User extends Model {

  @PrimaryGeneratedColumn()
  id: number;

  @Column({ unique: true })
  username: string;

  @CreateDateColumn({ name: 'created_at' })
  createdAt: Date;
}

For more details about field decorators. Check http://typeorm.io

After creating that model register it in src/server/models/index.ts

src/server/models/index.ts

export * from './User';

To create a record and query to database you need to use a SqlService with the model.

src/server/services/UserService.ts

import { SqlService } from 'exort/db';
import { User } from 'app/server/models';

export class UserService extends SqlService<User> {

  protected entity = User;
}

When importing models use app/server/models. It doesn't offer any feature but its better to have that import as it is easier than doing relative path.

Now to use the service inside a controller you need to bind it.;

src/server/http/controllers/HomeController.ts

import { HttpController } from 'exort/web';
import { Bind } from 'exort/core';

export class HomeController extends HttpController {

  @Bind(type => UserService)
  private userService: UserService;

  public async index() {
    let user = await this.userService.findOneById(1);
    this.response.render('index', { name: 'exort', user });
  }
}

7. Session

HTTP Controllers have session protected property that will allow you to manage session data. You can configure its storage by editing values in src/server/config/session.ts. If store.driver attribute is empty it will use memory as driver and will ignore connection attribute. For more information about configuration, please check https://github.com/expressjs/session.

src/server/config/session.ts

/**
 * The session store configuration
 * @type {Object}
 */
store: {
  driver: 'redis',
  connection: {
    host: env('REDIS_SESSION_HOST', 'localhost'),
    port: env('REDIS_SESSION_PORT', 6379),
    prefix: env('REDIS_SESSION_PREFIX', 'app-sess-local:')
  }
}

To manage session use session object or request.session inside HTTP Controller. session object is only available to HTTP controllers by default unless you pass it as reference to services etc.

To delete a session:

this.session.delete('key')

To get a data from session:

this.session.get('key')

To set a data:

this.session.set('key', 'value')

To check if a key exists

this.session.has('key')

You can also use flash session to automatically delete a session data once you retrieved it. This is useful for showing error messages or using session as flag data.

To set a flash data:

this.session.setFlash('key', 'value')

To mark an existing session data as flash

this.session.markAsFlash('key')

To check if a session data is a flash data:

this.session.isFlash('key')

Flash data are still just session data. The only difference is once you this.session.get('key') a flash data it will be automatically deleted from session.

8. Request Input

HTTP Controllers have input object. Input object allows you to get data from request like POST, GET data. Input object is only available in HTTP Controller unless you pass it as reference to services etc.

To get data from POST / GET request:

let value = this.input.get('key')

This will only get data from the current request method. For example, if the page is requested using POST this.input.get('key') will only get from POST data. This won't include file data.

You can also use dot notation if the request data is nested like JSON

let data = this.input.get('key1.key2')

To get all from current request method

let data = this.input.all()

You can also get all and exclude a key

let data = this.input.except(['key1', 'key2'])

Get only specified keys

let data = this.input.only(['key1', 'key2'])

To check for existing data:

this.input.has('key')

To get a file data:

let file = this.input.file('key')

To get multiple files:

let files = this.input.files('key')

To check if file exists:

this.input.hasFile('key')