npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

kk-koa-framework

v3.1.9

Published

kk koa mvc webframework

Downloads

51

Readme

kk-koa-framework

3.1.6 版本改动

增加Redis hget方法

3.1.1 版本改动

app启动可绑定ip,可以在config配置中添加hostname字段

module.exports = {hostname:"x.x.x.x"}

node app.js --hostname x.x.x.x

3.1.0 版本改动

添加createMethod,createMeta方法,可以增加编辑器代码提示功能

enableWebpack 方法需传入webpack包 ,可选传入webpack-dev-middleware以美化输出

app.enableWebpack(require('path to webpack.config.js'),require('webpack'),require('webpack-dev-middleware'))

2.1.7 版本改动

redis重试机制,改为使用retryStrategy

2.1.5版本改动

新增命令行设置端口:

node app.js --port 6880 或者 node app.js --port=6880

如果pm2启动:

pm2 start app.js -- --port 6880 或者 pm2 start app.js -- --port=6880

优先级:命令行参数=>配置文件=>默认端口(6880)

2.1.3版本改动

1.新增 ctx.request.xIp 变量 ,变量值为nginx透传的 x-forwarded-for 或者 x-real-ip

2.1.1版本改动

  1. 新增 ctx.state.lifttime 变量,变量值为app启动时的时间戳

  2. 新增 ctx.state.static_for 方法,使用方式示例:

script(src=static_for("js","index.js") ) 结果为: <script src="/js/index.js?v=123131313" />

link(href=static_for("css","index.css") ) 结果为: <link href="/css/index.css?v=123131313" />

如果需要加前缀需在 config/env/${env}.js 中添加属性: publicPath:"/prefix"

script(src=static_for("js","index.js") ) 结果为: <script src="/prefix/js/index.js?v=123131313" />

tips: NODE_ENV=development环境将移除缓存策略

2.0版本更新

1. redis 配置改动,redis字段为全局字段,session和fastCache默认不开启

redis:{
        host:'127.0.0.1',
        port:6379,
        db:1,
        password:'youknowthat',
        ttl : 20 * 60,
    },
    session:{
        prefix:'kk/session'
    },
    fastCache:{
        prefix:'kk/cache'
    }

2. fastCache访问

ctx.cache.set(id,obj,ttl)

id:唯一id号 obj:JSON对象 ttl:过期时间(-1 不过期,默认为redis字段的ttl)

ctx.cache.get(id) => json对象

ctx.cache.destory(id) 销毁fastCache


安装 | Install

	$ npm init
	$ npm install kk-koa-framework
    $ kk-init

创建所需要的文件夹

目录结构如下:

|-- kk-koa
    |-- app.js    <-- 入口文件
    |-- package-lock.json
    |-- package.json
    |-- assets	  <-- 静态资源存放路径
    |-- config	
    |   |-- routes.js    <-- 路由配置文件
    |   |-- env
    |       |-- base.js    <-- 环境配置文件
	|-- src
    |   |-- controller
    |       |-- index.js    <-- 控制器文件
    |-- views
        |-- index.pug    <--pug 静态模板文件

初始化 | Init

app.js作为一个默认的入口文件,只需简单的引入kk-koa框架并注册

const Koa = require('kk-koa-framework')
let app = new Koa()
app.setup().startup()

框架会自动完成各类初始化事件

文件详解 | Detail

config/env/base.js

base.js作为一个环境配置文件,存放一些和环境有关的配置项 示例代码:

module.exports = {
    session:{
        adapter : 'redis',
        password:'youknowthat',
        host: '10.0.3.24',
        port : 6379,
        db : 1,
        ttl : 20 * 60,
        prefix:'kk/test'
    },
    port:3344
}

src/controller/index.js

controller里面写对应的方法,示例代码如下:

module.exports.hello = async(ctx) => {
    ctx.body="hello world"
    console.log("print...")
}

config/routes.js

routes.js里面可以写各种路由规则,语法非常简单,示例代码如下:

module.exports = {
    'post /login':'index.login',
    'get /':'index.hello'
}

使用module.exports向外导出成模块。 语法为一个json格式的键值对key:value key: 请求类型(post,get) /路径 value:调用的方法,值为一个对象。该值默认为src/controller/index.js 中导出的方法
如:index/login表示cntroller下的默认index.js文件中的login方法

渲染pug文件

Pug语法可以参考:Pug中文文档

假设views/index.pug默认如下

doctype html
html
    head
    body
        .div Welcome To KK WEB FRAMEWORK
        div Hello #{user.nickName}

要渲染pug文件,我们首先在controller/index.js里写对应的方法

module.exports.showHome = async(ctx) => {
    ctx.state.user = {      //通过ctx.state转值
        nickName:"Lemon",
        age:21
    }
    await ctx.render('index')   //通过ctx.render()完成渲染,默认为view目录,
                                //传入的变量为文件名,默认文件后缀为.js
}

然后在config/routes.js中写相应的路由:

module.exports = {
   'get /':'index.showHome'
}

随后我们运行app.js入口文件

$ node app.js

访问localhost:3344 可以看到pug模板文件已经被渲染并显示:

Welcome To KK WEB FRAMEWORK
Hello Lemon

Post / Get请求

做一个小小demo,模拟表单提交:

doctype html
html
    head
        title 欢迎你 --- #{user.username}
    body
        div #{text}
        form(method="post" action="/login")
            span post 请求
            br
            input(type="text", name="username" placeholder="please enter username")
            br
            input(type="password", name="password" placeholder="please enter password")
            br
            input(type="submit", value="submit")

controller中写对应的方法

module.exports.showHome = async(ctx) => {
    ctx.state.user = {     
        nickName:"Lemon",
        age:21
    }
    await ctx.render('index')   
}

module.exports.getDate = async(ctx) => {
    let {username,password} = ctx.request.body
    ctx.body = {
        username:username,
        password:password
    }
    console.log(`username:${username}`)
    console.log(`password:${password}`)
}

写完controller后开始写对应的路由。 路由有两种方式,一种是上文提到的写在config/routes.js

module.exports = {
    'get /':"index.showHome",
    'post /login':'index.getDate'
}

或者直接在controller通过设置全局meta对象进行配置:

module.exports.meta ={
    getDate:{
        url:'/login',
        methods:['post'],
        bodyParser:true
    }
 }

注意:通过这种方式定义的路由,如果要解析的参数传递方法为post,则需要在controller中配置bodyParser:true

运行入口文件

$ node app.js

我们会看到控制台输出了usernamepassword的值

session

kk-koa框架将session存放在radis中,因此,使用session需要先安装并连接到redis

session配置

/config/env/base.js配置redis中的相应变量:

module.exports = {
    session:{
        adapter : 'redis',
        password:'password',
        host: '127.0.0.1',
        port : 6379,
        db : 1,
        ttl : 20 * 60,
        prefix:'kk/test'
    },
    port:2333
}

session方法

session是上下文(Context)中的一个对象,对象暴漏了几个常用的方法: session.save() 保存session session.destroy() 销毁session session.refresh() 刷新session防止过期

小demo,模拟登陆注册,实现: 如果未登陆,直接跳转到登陆界面。若已登录则显示登陆的用户名: index.pug

doctype html
html
    head
        title 欢迎你 --- #{username}
    body
        div 欢迎你 --- #{username}
        a(href="/logout") 注销

login.pug

doctype html
html
    head
        title 欢迎登陆
    body
        div #{title} , #{msg}
        form(method="post" action="/checklogin")
            br
            input(type="text", name="username" placeholder="请输入你的用户名")
            br
            input(type="password", name="password" placeholder="请输入你的密码")
            br
            input(type="submit", value="submit")

controller控制器:controller/index.js

module.exports.showLogin = async(ctx) => {
    await ctx.render("login",{
        title:"你好",
        msg:"欢迎登陆..."
    })
}
module.exports.checklogin= async(ctx)=>{
    await ctx.render("index")
    let {username,password} = ctx.request.body
    if( xxx ){ //写相应的判断 
        ctx.response.redirect('/index') //登陆成功后路由跳转
        ctx.session.profile = {     //给session存入一些自定义字段
            username:username,
            isLogin:true
        }
        ctx.session.save()  //保存session到redis中
    }else{
        console.log("用户名或密码错误")
        ctx.response.redirect('/')  //登陆失败,跳转到登陆界面
    }
}
module.exports.show = async(ctx) => {
    let session = ctx.session
    let isEmpty = JSON.stringify(session)=="{}"?true:false
    if(!isEmpty){   //判断是否存在session,不存在即为未登录
        let isLogin = ctx.session.profile.isLogin
        if(!isLogin){
            console.log("你还未登陆")
            ctx.response.redirect("/")
        }else{
            ctx.state={  //通过ctx.state传值给pug模板
                username:ctx.session.profile.username
            }
            console.log("登陆成功")
            await ctx.render("index")
        }
    }else{
        console.log("你还未登陆")
        ctx.response.redirect("/")
    }
}
module.exports.logout = async(ctx) => {
    ctx.session.destroy()   //销毁session
    ctx.response.redirect('/')
}

路由:config/route.js

module.exports = {
    'get /':"index.showLogin",
    'post /checklogin':"index.checklogin",
    'get /index':"index.show",
    'get /logout':"index.logout"
}