Using OpenResty to build a simple Web API framework, easy to use later when quickly generate project structure

The project address

Click here to

The directory structure

Structure for containing config, controller, libs, model four directories

  • config

    Configuration file directory for APP, Redis, Database related configuration

    • APP application related
    Return {default_controller = 'home', -- default controller default_action = 'index', -- default method}
    • Database correlation
    Local mysql_config = {timeout = 5000, connect_config = {host = "127.0.0.1", port = 3306, database = "demo", user = "root", password = "a12345", max_packet_size = 1024 * 1024 }, pool_config = { max_idle_timeout = 20000, -- 20s pool_size = 50 -- connection pool size } }
    • Redis configuration
    Return {host = "127.0.0.1", -- Redis host port = 6379, -- the port max_idle_timeout = 60000, -- max idle time pool_size = 1000, -- pool size timeout = 1000, -- timeout time db_index= 2, -- database index }
  • Libs directory

    Common module libraries under the libs directory, including redis, db, request, response, etc

  • The controller directory

    This is the controller directory, which contains a encapsulated Base class base. lua, which the business controller can inherit. The basic business controller code is as follows

    -- home.lua
    local Base = require("controller.base")
    
    local Home = Base:extend()
    
    function Home:index() 
        self:json({data={}})
    end

    //home/index = ‘index’; //home/index = ‘index’; //home/index = ‘index’; //home/index = ‘index’;

    There are a few basic properties provided in Controller

    • Self. Request gets relevant parameters of the request, such as self.request.query.XX gets GET parameters, self.request.body.XX gets POST parameters, self.request.headers. XX gets header parameters, etc
    • Self. Response outputs the response results, mainly including self.response:json() to return data results,self.response :redirect() jump,self.response

      In order to facilitate development, Response is encapsulated in Base, providing two shortcut methods self:json() and self:error(code,message)

      Self :json({data=self.redis:get("test")}) data self:error(2," data to get data"

      The returned structure contains the data,code, and message fields

      {" data ": {" data" : [" BBBBB ", "B", "AAAAA", "A", "BBBBB", "B", "AAAAA", "A"]}, "message" : ""," code ":" success "}
    • Self. Redis can use redis, including self. Redis: set, the self. Redis: get, self. Redis: hset, self. Redis: hget, etc. See lines 15 to 72 of the libs/redis.lua file for details on the functions you can use
    • Self. Controller gets the name of the current controller
    • Self. Action Gets the name of the current Action operation
  • The model directory

    Model correlation, for ease of operation, also encapsulates a Base class, the business model only needs to inherit

    -- good.lua local Base = require "model. Base "local good = Base:extend() -- Base return good ("test",'lgid') The first argument is the name of the table, the second argument is the primary key of the table (default is id).

    The Base class encapsulated in base. lua provides methods for adding, deleting, modifying, and searching a single table

    • Create (data) to add a record
    • Delete (id) deletes the record
    • UPDATE (data,id
    • Get (), all() filter records
    • Where () filter condition method
    • Columns () sets the method to find which columns
    • OrderBy () sets the sorting method
    • Count () Finds the total number of data items

    Base.lua also provides a method for customizing the execution of SQL to facilitate complex queries

    • query()

Quick start

  • Nginx.conf adds code similar to the following

    worker_processes 1; error_log logs/error.log; events { worker_connections 1024; } http { lua_package_path 'E:/openresty/demo/src/? .lua;; '; server { charset utf-8; listen 8080; location = /favicon.ico { log_not_found off; Access_log off; } location / {default_type text/ HTML; content_by_lua_file "E:/openresty/demo/src/main.lua"; }}}
  • Add Controller

    Add User. lua in the Controller directory

    local Base = require("controller.base")
    
    local User = Base:extend()
    
    function User:index() 
        self:json({
            data={
                name = "hello world"
            }
        })
    end
    return User
  • Add the model

    local Base = require "model.base"
    
    local User = Base:extend()
    
    return User("sls_p_user",'suid')
  • The Controller uses the Model

    local userModel = require('model.user')
    
    function User:index() 
        self:json({
            data={
                name = userModel:columns('rname'):get(1)
            }
        })
    end

Description of the shortcut encapsulated by the model

  • add

    local data = {
        name = "test",
        pwd = 123
    }
    local insertId = userModel:create(data)
  • delete

    • Delete by primary key

      local affect_rows = userModel:delete(2)
    • Delete according to WHERE condition

      local affect_rows = userModel:where("name","=",3):delete()
  • Modify the

    • Modify according to primary key

      Local affect_rows = userModel:update(data,2) local data = {suid = "1", -- data has primary key, } local affect_rows = userModel:update(data)
    • Modify according to WHERE condition

      local affect_rows = userModel:where("name","=",3):update(data)
  • To find the

    • Find a record

      Local info = userModel:where("name","=",3):get() local info = userModel:get(1) local info = userModel:get(1) local info = userModel:get(1 Local Info = UserModel: Columns ({'suid','name'}):get(1) Select * from table where (select table from table)
    • Find multiple records

      Local List = UserModel: COLUMNS ('suid ', 'name'):all() Local list = userModel: Columns ({'suid','name'}):all() Local list = userModel: Columns ({'suid','name'}):all(
  • Description of other methods

    • Find the number of data bars

      local count = userModel:where("name","=","json"):count()
    • The sorting

      local list = userModel:where("name","=",3):orderby("id"):all() local list = UserModel: where (" name ", "=", 3) : orderby (" name ", "asc") : orderby (" id ", "desc") : all () - multiple sort
    • Find the specified field (if not used, find all fields)

      Local list = userModel: Columns ('suid,name'):all() -- Columns
    • Find according to the WHERE condition

      local list = userModel:columns('suid,rname'):where("suid","<","30"):orderby("suid"):all() local list = UserModel: columns (' suid, rname) : the where (" suid ", "<", "30") : the where (" rname ", "like", "test %") : orderby (" suid ") : all () - more than can the where
    • Customize the SQL executed

      SQL = "select su.*,c.logincount from sls_p_user su join c_user c on su.suid=c.suid where su.suid=2" local SQL = "select * from sls_p_user where suid=? and username=?" local result = userModel:query(sql,{1,"json"})

The command line

In order to facilitate the rapid generation of controller controller and model, the command line is specially developed. The command line is written in Luajit, which needs to be put into the environment variable

./ jFrame -h JFrame v0.1.1, a Lua Web Framework based on OpenResty. Usage: JFrame COMMAND [OPTIONS] Commands: controller [name] Create a new controller model [name] [table] Create a new model version Show version of the framework help Show help tips

Note that under Windows the command is

luajit ./jframe -h
  • Generate controller, automatically generated to the controller directory

    jframe controller controllerName
  • Generate model, automatically generate to model directory

    JFrame Model ModelName -- does not specify the table name, the generated model table name is the given modelName in lowercase format by default JFrame Model ModelName Table -- specifies the modelname and table name