今天开始写一下 strongloop 框架的使用 从创建model开始写吧。。前面类似环境配置及项目创建的部分请自行补脑。
写给像我这样小菜菜的 高手及老鸟 请绕。。。。。。
创建Model部分
在项目 目录下输入 slc loopback:model
提示如下
- Model name:model名称
- Data source: 数据源 选择就行
- Base class: 选择依赖模型。这里也可以CUSTOM 。。。你懂得 这里注意一下 如果选择其他类型 则是对该类型进行扩展
- Expose model名称 via the REST API? 回车就行
- Custom plural form (used to build REST URL): 回车默认
- Enter an empty property name when done.
- ? Property name:username
- invoke loopback:property
- ? Property type:string
- ? Required?Yes //重要 是否必须
创建后终端 一定要记得slc run
再打开api explorer 可以看到刚建的 model已经有了
PS:其实这里我们所用的向导所设置的文件在 项目commom/models目录下 可以找到刚刚我们建的model
当然 因为我们设置了数据源 所以server/model-config.json里也会出现。这里也可配置具体权限 (这里稍后再细看)。
这里基本的属性都已经有了 但是我们还需要扩展一下 。
上面我们说过 在commom/models 目录下能找到我们定义的Model
这里我们可以看到一个Model对应两个文件 一个JS文件及一个JSON文件
其中 JSON文件描述整个Model的属性 还有ACL (ACL 是访问权限控制 也是稍后再细看)
另一个JS文件则是我们定义的Model定义逻辑用的。。这里主要看下这个文件
这里我扩展了一下默认的USER类型 为userplus
发现如果使用默认的user 数据库表中插入的数据是不全的。。所以我们扩展一下 附加数据插入时间 (created) 字段
先定义这是个扩展方法
Userplus.remoteMethod(
'CreateUserPlus',
{
description: '创建自定义用户',
accepts: [
//{arg: 'credentials', type: 'object', required: true, http: {source: 'body'}},
{arg: 'data', type: 'object', http: {source: 'query' },
description: '参照model定义'}
],
returns: {
arg: 'state', type: 'string', root: true,
description:
'返回描述'
},
http: {verb: 'post',path: '/Userplus'}
}
);
然后写相应的方法
Userplus.CreateUserPlus=function (data, cb){
options = data || {};
if (typeof data.email === 'string'
||typeof options.username === 'string'||typeof options.password === 'string'
) {
Userplus.findOne({ where: {email: data.email} }, function(err, user) {
if (err) {
cb(err);
} else if (user) {
//存在
var err = new Error('email has...');
err.statusCode = 400;
//err.code = 'EMAIL';
cb(err);
} else {
Userplus.create({
email: data.email,
password: data.password,
username:data.username,
created:moment().format("YYYY-MM-DD HH:mm:ss")
});
cb(err,"REG_OK");
}
});
} else {
var err = new Error('email username password is required');
err.statusCode = 400;
err.code = 'EMAIL_REQUIRED';
cb(err);
}
};
这样 一个扩展方法就写好了
代码预览 折叠了一下 其中顶部 moment为 时间格式辅助库 详见 http://momentjs.com/
我们去 API explorer 试一下
提交成功 数据库成功写入 这样 一个简单的用户注册就做完了。 可以配合AngularJS 使用 可用辅助工具生成相应service 很是方便。
移动终端的话 strongloop配有相应的SDK 这些以后介绍
补充: 这里可能无法进行数据提交 提示401 错误 因为我们没有设置ACL
控制台输入
slc loopback:acl
提示如下
- ? Select the model to apply the ACL entry to: customuser
- ? Select the ACL scope: A single method
- ? Enter the method name: CreateUserPlus
- ? Select the role: Any unauthenticated user
- ? Select the permission to apply: Explicitly grant access