Front-end web system rapid development framework: @oneline/core quick guide

Front-end web system rapid development framework: @oneline/core quick guide

@oneline/core

A view layer framework based on fastify . We use typescript to complete the development.

install

   npm install @oneline/core;
   //or
   yarn add @oneline/core;
 

quick guide

1.First we create a control: index.ts currently we default application/jsonresponse data.

  import {Get, HttpResult} from '@oneline/core';
  
  class Index {

    @Get("/index", " ")
    public index() {
      return HttpResult.ok({message: ' ', data: []})
    }

  }
 

2. Create a project startup entry: app.ts

  import {start} from '@oneline/core';
  import './index';


  start(3000);
 

3. Start

  node app.js
 

Interface Description

start

 const app = start(port: number, options: WayOptions, filters: HttpFilter[]);
 

app is the fastify instance object. You can add related functions according to the fastify function

WayOptions

This type includes: db, cors, staticfield.

dbIs the database configuration object. The database fields contain:

{
  host: string;
  port: number;
  username: string;
  password: string;
  database: string;
}
 

host : server address

port : database port

username : username

password : password

database : database name

The database currently only supports mongodb.

cors Cross-domain configuration. The main fields are as follows:

{
  origin?: string|string[]|Boolean|Function;
  methods?: string|string[];
  allowedHeaders?: string|string[];
  exposedHeaders?: string|string[];
  preflight?:Boolean,
  credentials?: Boolean
}
 

The fields are optional. The function of each field can be viewed in the MDN document

static: Configure static file path. Configure static file read path and request prefix.

{prefix: string, path: string}
 

prefix is the request prefix, the default is static . There is no need to add a diagonal bar ( / ) as a starting point.

path is the directory of static files.

HttpFilter

abstract class HttpFilter {
  abstract chain(app:FastifyInstance, request: FastifyRequest<IncomingMessage>, response: FastifyReply<ServerResponse>, key?: String, bean?: ComponentBean):Promise<{success: boolean, message: string, break?:boolean, code?:string}>;
}
 

HttpFilterAs a filter, it is an abstract class that needs to be implemented. Here you can add system filters according to your needs.

Request comment function

@Action

  Action(options: ComponentActionOptions)
 

ComponentActionOptions Types mainly have the following fields:

  path: string; //View   
  method: any; //   
  paramtypes?: Array<any>; //
  paramNames?: Array<string>;//
  params?: object;
  actionName?: string;
  marker?:boolean;
  response?: HttpResponseHeader;
 

Action .

@Get

  Get(path: string | ComponentActionOptions, actionName?: string, marker:boolean = false)
 

path : When it is a string, this is the routing path. If it is a ComponentActionOptions object, the same as above.

actionName : The function description of the function.

marker : trueas a grouping marker, otherwise it is a function function

@Post

Same as above

@OPTIONS

Same as above

@Delete

Same as above

Parameter annotation

@Param

Parameter matching mapping. This includes request link parameters and entity class content. Param can be used to map to function parameters.

  //: http://api.weixin.qq.com/sns/login?type=wechat
  public login(@Param('type') type: string) {
    console.log(type); // wechat
  }

  //
  public login(@Param('type') loginType: string) {
    console.log(loginType); //wechat
  }
 

@Body({rule: object, query: object})

Entity class mapping. It is mainly used for restricting rules before inserting entity classes into the database.

rule It is the object of the verification rule. It is mainly the entity data in the post request.

query Is the parameter in the request link.

Verify entity class

regx : regular expression. Regx has the highest priority. If regx is set, the default format verification such as email and required will be ignored.

readonly : Read-only setting. Automatically generated by default. You can also specify value:(():any)to implement it yourself.

required : Can not be empty for verification. If you need to check whether it exists in the database, addconnect: {dao: Dao, method: string, key: string}

email : Email verification

unique : unique verification. Need to compare the data situation of the database {dao: Dao, method: string, key: string, self: boolean}. If self is true, it represents the update status. You do not need to compare with yourself.

example


 class SignUser {
   uid: string = "";
   username: string  = "";
   password: string = "";
   createTime: number = Date.now();
   from: string = "";
 }

 const SignRule = {
   signup: {
     uid: {
       label: " ID",
       rules: [
         {readonly: true}
       ]
     },
     username: {
       label: " ",
       type: String,
       rules: [
         {required: true, message: ' '}
       ]
     },
     password: {
       label: " ",
       type: String,
       rules: [
         {regx: /\w{6, 8}/, message: " 6~8 "}
       ]
     },

     from: {
       label: ' ',
       type: String,
       rules: [
         {required:true}
       ]
     }
   }
 }

 // from,  url . http://localhost:3000/signup?platform=app
 class SignMarker {

   @Post("/signup", " ")
   signup(@Body({rule: SignRule.signup, query: {platform: 'from'}}) user: SignUser) {
     return HttpResult.ok({message: ' '});
   }

 }

 

If the conditions are not met, an error will be reported! The function body will not be executed, and the registration success will not be returned.

Attribute annotation

@Property

Property annotations are used to automatically inject objects, without having to create objects manually.

   class Test {
     public todo() {
       console.log("todo...")
     }
   }

   class TestIndex {
      @Property() test: Test;
      public index() {
         this.test.todo();
      }

   }

 

mongo database operations

Database operation, we need to configure the database link when starting

  star(3000, {
    db: {
      host: '127.0.0.1',
      port: 3690,
      database: 'oneline',
      username: 'root'
      password: '123456'
    }
  })
 

In terms of operation, we built a service layer and database (Dao) operation layer.

service

DefaultService<T>This is an abstract class that implements interfaces Service<T>. We can also implement Service<T>interfaces, and inheritanceDefaultService<T>existing methods of operating the database.

dao

DefaultDao<T>This is an abstract class that implements the interface Dao<T>. We can also implement the Dao<T>interface, and inherit the DefaultDao<T>existing methods of operating the database.

example

  
  public class User {
    uid: string = "";
    uname: string = "";
    upass: string = "";
    createTime: number = Date.now();
  }


  public class UserDao extends DefaultDao<User> {
    table: string = "ol-user";
  }


  public class UserService extends DefaultService<User> {
    @Property() dao: UserDao<User>;
  }


  public class UserAction {
    @Property() service: UserService;

    @Post("/user/signup")
    public async signup(@Body() user:User) {
      await this.service.save(user);
      return HttResult.ok({message: " "});
    }
  }