Skip to content

synder/xpress

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

91 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

xpress

What is xpress?

  • Api Framework A node.js api framework base on express which provide api route version and channel control
  • Web Framework A node.js web framework base on express and art-templete, and expand many usefull view helper

Install

$ npm install -g xpress

Sample code

there are two full sample projects in /sample/api and /sample/web

Run sample project

#cd ./sample/api
cd ./sample/web 
npm install 
node app.js

open http://127.0.0.1:8001/, there are many template engine(base on artTemplate) view helper sample code

Create project with commander

npm install -g xpress
cd /<project path>
xpress -p ./ -t (api | web)
npm install
npm start

APi

create an api server with xpress

//import module
var Xpress = require('Xpress');
var config = require('./config');
//create server
var server = new Xpress({
    host: null,
    key: null,
    cert: null,
    trace: true, //open route trace
    port: {
        http: 8001,
        https: null
    }
});
//configure
server.conf('x-powered-by', false);
server.conf('trust proxy', true);
server.conf('views', config.public.server.view.path);
server.conf('view engine',config.public.server.view.engine);
server.conf('view cache', false);
server.engine('html', Xpress.engine.__express); 

Xpress.engine is equal require('art-template/node/template-native.js')

//use middleware
var body = require('body-parser');
var cookie = require('cookie-parser');
var timeout = require('connect-timeout');
var compression = require("compression");
var statics = require('express-static');
server.use(compression());
server.use(timeout('20s'));
server.use(cookie());
server.use(body.json());
server.use(body.urlencoded({extended: true}));
server.use(statics(config.public.server.statics.path));
//register an api on a controller with version or channel control
//'v' represent version and 'c' represent channel
//if you register an api with version and channel control, 
//you must set 'X-Accept-Version' and 'X-Client-Channel' on request header, 
//xpress will get the two value from the header and compared with the register v and c
//if not equal, xpress will skip the controller and jump to the next controller which has registered the same route
//you can get and set the two headers on Xpress.defaults.versionHeader and Xpress.defaults.channelHeader
server.get('/user', {v:1.0, c: 'ios'}, function(req, res, next){
    res.json({
        users: []
    });
});
//register an api on a controller without version and channel control
server.get('/user/:id', function(req, res, next){
    res.json({
        name: 'synder',
        age : 29
    });
})
//create a sub router and register on server
var Router = Xpress.Router;
var productRouter = new Router();
//register an api on subRouter without version or channel control  
//import utils 
var string = Xpress.string;
var parser = Xpress.parser;
var validate = Xpress.validate;
productRouter.get('/', function(req, res, next){
    if(validate.isPassword(req.query.pass)){
		res.json({
			bankCard: string.bankCard('6666666666666666')    
		});
	}
})
//register an api on subRouter with version or channel control  
productRouter.get('/:id', {v:1, c:1}, function(req, res, next){
    var id = parser.parseInt(req.params.id, 10);
    res.json({
        id: id
    });
})
server.sub('/product', productRouter); 
//error handler
server.error(404, function (err, req, res, next) {
    res.status(404).json('not found');
});
server.error(500, function (err, req, res, next) {
    res.status(500).json(err.stack);
});
//listen on host and port
server.listen(function(message){
    console.log(message);
});
//listen on host and port with cluster
//server.cluster(0, function(msg){
//    console.log(msg);
//});
//export
module.exports = server;

##Integration tools

parser

var parser = require('xpress').parser;
parser.parseTime('2016-06-22T04:42:07.228Z');
parser.parseDate('2016-06-22T04:42:07.228Z');
parser.parseDateTime('2016-06-22T04:42:07.228Z');
parser.parseInt('122', 100); //122
parser.parseInt('a122', 100); //100
parser.parseFloat('a122', 100); //100
parser.parseBool('a122'); //true
parser.parseBool('');     //false
parser.parseJson('{"name":"synder"}', null);     //{name:"synder"}
parser.parseJson('{"name":"synder}', null);     //null

fs

var fs = require('xpress').fs;
//get dir
fs.homedir(); //return user home dir
fs.tmpdir();  //return system temp dir
//get file name or dir
fs.filename(path);  //return file name 
fs.filedir(path);   //return dir name
//node navtive fs method
fs.createReadStream();
fs.createWriteStream();
fs.chmod();
fs.chown();
fs.link();
fs.unlink();
fs.utimes();
fs.stat();
fs.access();
fs.watch();
//fs extend method
fs.exists(path, callback);
fs.mkdir(path, [opt], callback);
fs.list(path, iterator, callback); //list file or dir in path
fs.walk(path, iterator, callback); //list all file in path and child path
fs.read(path, callback);
fs.readline(path, iterator, callback); //read file by line
fs.save(path, content, [opt], callback);
fs.append(path, content, [opt], callback);
fs.touch(path, [opt], callback);
fs.copy(src, dst, callback);  //copy file or dir
fs.move(src, dst, callback);  //cur file or dir
fs.rename(old, newName, callback);
fs.md5(filepath, callback);
fs.fetch(webUrl, dst, [filename], callback); //get file from web

validate

var validate = require('xpress').validate;
validate.isNull(str)
validate.isUndefined(str)
validate.isNullOrUndefined(str)
validate.isDate(val)
validate.isArray(val)
validate.isString(val)
validate.isNumber(num)
validate.isFunction(val)
validate.isNaN(val)
validate.isRegExp(val)
validate.isBool(val)
validate.isInt(num)
validate.isFloat(num)
validate.isObject(obj)
validate.isDictionary(obj)
validate.isBuffer(obj)
validate.isSymbol(str)
validate.isRequired(str)
validate.isMobile(str)
validate.isEmail(str)
validate.isPassword(str)
validate.isChinese(str)
validate.isBankCard(str)
validate.isChineseIdCard(str)
validate.isIPV4Address(str)

string

var string = require('xpress').string;
string.date(new Date(), '-')              //2016-04-20
string.time(new Date(), ':')              //10:03:20
string.dateTime(new Date(), '-', ':')     //2016-04-20 10:03:20
string.format('%s name is', 'synder')     //synder name is
string.pad('12222', 10, '0', 'left')      //'0000012222'
string.pad('12222', 10, '0', 'right')     //'1222200000'
string.pad('12222', 10, '0', 'both')      //'0001222200'
string.unit(10, 'px')                     //10px
string.mask('18083489462', '*', 4, 5)         //180*****442
string.join('', null, 10, undefined, 20, '+') //10 + 20
string.trim('  name  ')        //name
string.quote("name", '"')      //"name"
string.clean('my   name  is')  //my name is
string.lines('my\rname\ris')   //['my', 'name', 'is']
string.signed(10)    //+10
string.signed(-10)   //-10
string.stringify()
string.truncate('122212313213132132', 13, '...') //1222123132...
string.capitalize()
string.upperCase()
string.lowerCase()
string.currency(242605401.001, '$', 3)     //$242,605,401.001
string.chineseCurrency('90002600401.001')  //玖佰亿零贰佰陆拾萬零肆佰零壹
string.thousands(242605401.001)         //242,605,401.001
string.bankCard('233546454633344332')   //2335 4645 4633 3443 32
string.percentage(0.5)                  //50%
string.percentage(0.5, 2)               //50.00%
string.number(0.5, 3)                   //0.500

View helper(base on art-template)

<%= $dateTime(new Date())%> 2016年06月07日 11时56分38秒
<%= $dateTime(Date.now())%> 2016年06月07日 11时56分38秒
<%= $Math.random()%> 0.035149546630335315
<%= $toString([1,2,3])%> [1,2,3]
<%= $parseInt('10', 0)%> 10
<%= $parseInt('NA0122', 0)%> 0
<%= $parseInt('NA0122')%> null
<%= $parseFloat('12.3')%> 12.3
<%= $parseFloat('a12.3', 0)%> 0
<%= $format('%s %X', 'sam', 1000)%> sam 0x3E8
<%= $format('%s %o', 'sam', 1000)%> sam 01750
<%= $format('%s %d', 'sam', 1000)%> sam 1000
<%= $format('%s %b', 'sam', 1000)%> sam 1111101000
<%= $format('%c %c', 'sam', 98)%> sam b
<%= $format('%s %2f', 'sam', 98)%> sam 98.00
<%= $format('%s %j', 'sam', {name:1})%> sam {"name":1}
<%= $toString(null)%>
<%= $toString({name: 1})%> {"name":1}
<%= $toString([12,3])%> [12,3]
<%= $join('10', '2', '6', '+')%> 10+2+6
<%= $join('10', null, '6', '9', '+')%> 10+6+9
<%= $join(null, null, '6', '+')%> 6
<%= $join(null, '6', '', '+')%> 6
<%= $trim(' name ')%> name
<%= $mask('18083489462', '*', 4, 5)%> 180*****462
<%= $mask('18083489462', '*', -1, 5)%> 18083******
<%= $pad('12222', 10, '0', 'left')%> 0000012222
<%= $pad('12222', 10, '0', 'right')%> 1222200000
<%= $clean(' 122 22 ')%> 122 22
<%= $toString($lines('122\r\n22132'))%> [122,22132]
<%= $toString($lines('122\r22132'))%> [122,22132]
<%= $truncate('122212313213132132', 13, '...')%> 1222123132...
<%= $chineseCurrency('92102600401.001')%> 玖佰贰拾壹亿零贰佰陆拾萬零肆佰零壹
<%= $currency(242605401.001, '$', 2)%> $242,605,401.00
<%= $upperCase('AbddessSww')%> ABDDESSSWW
<%= $lowerCase('AbddessSww')%> abddesssww
<%= $capitalize('AbddessSww')%> AbddessSww
<%= $capitalize('AbddessSww', true)%> Abddesssww
<%= $bankCard('233546454633344332')%> 2335 4645 4633 3443 32
<%= $number(0.5, 3)%> 0.500
<%= $thousands(2783619263)%> 2,783,619,263
<%= $percentage(0.5)%> 50%
<%= $percentage(0.523366, 2)%> 52.34%
<%= $urlPathVersion('/name', 10)%> /name?version=10
<%= $urlPathJoin('/name', '//age')%> /name/age
<%= $urlFormat('/home', {name:1}, 'http', '127.0.0.1')%> http://127.0.0.1/home?name=1
<%= $urlFormat('/home', {name:1})%> /home?name=1
<%= $encodeURIComponent('/测试 账号')%> %2F%E6%B5%8B%E8%AF%95%20%E8%B4%A6%E5%8F%B7
<%= $decodeURIComponent($encodeURIComponent('/测试 账号'))%> /测试 账号
<%= $encodeURI('/测试 账号')%> /%E6%B5%8B%E8%AF%95%20%E8%B4%A6%E5%8F%B7
<%= $decodeURI($encodeURI('/测试 账号'))%> /测试 账号
<%= $date('2016-06-01T07:05:36.838Z', '-')%> 2016-06-01
<%= $time('2016-06-01T07:05:36.838Z', ':')%> 15:05:37
<%= $dateTime('2016-06-01T07:05:36.838Z', '-', ':')%> 2016-06-01 15:05:37
<%= $dateTime('2016-06-01T07:05:36.838Z')%> 2016年06月01日 15时05分37秒
<%= $isNull(null)%> true
<%= $isNull(undefined)%> false
<%= $isUndefined(undefined)%> true
<%= $isUndefined(null)%> false
<%= $isNullOrUndefined(null)%> true
<%= $isNullOrUndefined(undefined)%> true
<%= $isArray([])%> true
<%= $isDate(new Date())%> true
<%= $isDate('2012-03-01')%> false
<%= $isString('name')%> true
<%= $isString({})%> false
<%= $isString(null)%> false
<%= $isNumber(1)%> true
<%= $isBool(true)%> true
<%= $isInt(1.1)%> false
<%= $isInt(1)%> true
<%= $isFloat(1.1)%> true
<%= $isFloat(1)%> false
<%= $isObject(null)%> false
<%= $isObject({})%> true
<%= $isObject([])%> true
<%= $isDictionary([])%> false
<%= $isDictionary({})%> true

art-template

refer to art-template

express

refer to express.js