Sails基础之Controller层

article/2025/9/14 4:18:04

通过前面的使用,我们可以看出Sails中MVC的结构更倾向于MVP的概念,Presenter在Sails中被称之为Actions:

They often act as a middleman between your models and views.

Controller层这个结构上的变化是Sails v1.0中新提出的方案,Action可以使用classic和actions2两种格式,另外,仍然兼容支持Sails v0.12上的Controller实现方式。相对于肿胀的Controller,将Controller拆分成多个Action可以更清晰的表达业务逻辑,其中actions2格式的Action更是一种半文档半校验器的形式,可以从接口描述、接口参数、参数校验、逻辑、退出方式等方面构建整个业务逻辑。

Actions

Action2 Action

Action2格式的action与Helper基本相似,需要做调整的主要是各种与Controller层职责相关的exit方式。我们来创建一个signup action:

sails generate action user/login

我们可以编写一个用于登录验证的action,从而实现登录业务逻辑:

  1. Model层
    Model层我们使用前面案例中的User Model:
const crypto = require('crypto'); 
const uuid = require('node-uuid');module.exports = {primaryKey: 'uuid',attributes: {uuid: {type: 'string',required: true,},username: {type: 'string',required: true,allowNull: false,unique: true,},password: {type: 'string',required: true,allowNull: false,},},customToJSON: function() {return _.omit(this, ['password']);},beforeCreate: function (valuesToSet, proceed) {let md5 = crypto.createHash('md5');valuesToSet.uuid = uuid.v4();valuesToSet.password = md5.update(valuesToSet.password).digest('hex');return proceed();}};

身份验证主要通过对username和password的查询完成。
2. View层
首先在config/routes创建一个view路由:

 '/login': {view: 'pages/login',locals: {layout: 'layouts/users',errno: 0,},
},

该路由指定了模板为views/pages/login,layout为views/layouts/users(只有默认的ejs模板引擎支持此项配置),接下来我们分别创建layouts/users和pages/login:
layouts/users.ejs:

<!DOCTYPE html>
<html><head><title>Sails App</title><!-- Viewport mobile tag for sensible mobile support --><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><!--STYLES--><!--STYLES END--></head><body><%- body %></body>
</html>

pages/login.ejs:

<div class="container"><% if(errno == 1){ %><div class="alert alert-danger" role="alert">Username or password is error!</div><% } %><form method="POST" action="/user/login"><div class="form-group"><label for="username">Username</label><input type="text" class="form-control" id="username" name="username" placeholder="Enter username"></div><div class="form-group"><label for="password">Password</label><input type="password" class="form-control" id="password" name="password" placeholder="Password"></div><button type="submit" class="btn btn-primary">Submit</button></form>
</div>

assets资源:
将bootstrap.min.css拷贝到assets/styles下,启动时grunt任务会将其自动注入到users.ejs的样式文件引用中。

  1. Controller层
    api/controllers/user/login:
const crypto = require('crypto'); module.exports = {friendlyName: 'Login',description: 'Login user.',inputs: {username: {description: 'The username',type: 'string',required: true,},password: {description: 'The password',type: 'string',required: true,}},exits: {success: {responseType: 'view',viewTemplatePath: 'pages/welcome'},fail: {responseType: 'view',viewTemplatePath: 'pages/login'},err: {description: 'Occur error',responseType: 'notFound'}},fn: async function (inputs, exits) {let md5 = crypto.createHash('md5');let {username, password} = inputs;try{let user = await User.findOne({username, username});if(!user || user.password != md5.update(password).digest('hex')){return exits.fail({errno: 1});}return exits.success({errno: 0,msg: {username: username}});} catch(e) {sails.log(e.message);throw 'err';}}
};

可以看到与Helper的结构是一致的,唯一需要调整的是exit的方式,而exit方式主要是由responseType决定的:
responseType is one of the following:

  • “” (the standard response: Determine an appropriate response based on context: this might send plain text, download a file, transmit data as JSON, or send no response body at all.)
  • “view” (render and respond with a view; exit output will be provided as view locals)
  • “redirect” (redirect to the URL returned as the exit output)
    为action创建路由:
  'post /user/login': 'user.login',

从代码可以看到,登录成功后,渲染模板pages/welcome,因此,我们创建对应的模板:

<h1>Welcome <%= msg.username %> !</h1>

接下来,我们启动测试以下:

  1. 创建一个测试user:
    http://127.0.0.1:1337/user/create?username=admin&password=123456&uuid=auto

  2. 登录错误:
    http://127.0.0.1:1337/login

    输入错误的username或password:

  3. 登录成功:
    输入正确的username和password:

Classic Action

Classic action与v0.12版本中传统的Controller实现方式基本一致,将传统写在一个Controller中的业务逻辑拆分为单个的一个个action,更有利于业务的实现与维护。

sails generate action user/login--no-actions2

Controller

另外,你仍然可以使用传统的Controller方式实现所有业务逻辑:

module.exports = {login: function (req, res) { ... },logout: function (req, res) { ... },signup: function (req, res) { ... },
};

machine-as-action

你也可以将Controller的编写方式转换到action2的编写风格上来,请参考以下链接:
https://github.com/sailshq/machine-as-action


http://chatgpt.dhexx.cn/article/yT324cml.shtml

相关文章

二、 在Sails中使用Typescript

文章目录 Typescript 基础Typescript 安装TypeScript 问题最简单的改造 Sails重定义Waterline&#xff08;Orm&#xff09; 重写ModelsTypescript 重写控制器User Model的进一步优化前后端约定 路径别名tsconfig.jsonmodule-alias安装使用 Jest测试 Typescript 基础 Typescrip…

四、Sails项目的Api文档——集成Swagger解决方案

文章目录 Api的迷思SwaggerSwagger概述在Sails中集成Swagger安装Swagger 生成设置生成的内容SwaggerUI Assets和.tmpBlueprint 蓝图Blueprint是什么Blueprint 配置local.js 进一步控制Swagger输出路由过滤路由的Swagger配置进一步优化Authorization Api的迷思 我们都知道写代码…

sails mysql_Sails+MVC+Mysql+Node+学习笔记一

项目构建 安装Node就不多说了&#xff0c; 1.sails安装与项目新建运行 npm install sails -g//全局安装 sails new project-name//新建项目 cd project-name //进入刚才新建项目的目录 sails lift //运行项目&#xff0c;运行原理也是直接在项目目录路径下使用node app.js npm …

Sails.js自动化Api实践与测试

开发中为了快速交互数据库&#xff0c;于是需要一个能便捷搭建api的平台。于是学习了一下sails.js框架。本次实践是一次摸索&#xff0c;使用了winston日志记录&#xff0c;supertest单元测试&#xff0c;mongo数据库&#xff0c;hashids哈希值解密。 模块: winstonsupertestmo…

五、解读Sails之Waterline源代码

文章目录 sql调试代码跟踪package.json启动调试Auto-Migrating备份原始数据删除所有表再重建回写备份数据 加密库 encrypted-attraes-256-gcm算法encrypted-att 的使用密钥 sql转义 sqlstring日期处理三种方式比较mariaDB&#xff08;或my-sql&#xff09;中的日期时间string 对…

一、Sails基础操作

本篇目录 Sails 安装App结构修改端口跨域问题第一个Api控制器用Postman 做Api调试MySql命令行操作MySql8.0版本加密问题 Sails 操作Mysql创建第一个model实现一个model的增删改查 Sails 安装 Sailsjs提供安装脚手架&#xff0c;使用之前可以先安装Sailjs npm install sails -…

sails

sails介绍 node.js的MVC框架&#xff0c;完全继承Express&socket.io的一些API 使用 全局安装 npm install -g sails创建项目 sails new 项目名称选2 选2 启动项目 sails liftsails框架目录介绍 api MVC结构项目代码目录controller层controller层尽量只做数据封装&…

Sails基础之Models层的config/datastores配置

配置与使用 Sails提供并支持多种Models层的存储&#xff08;https://sailsjs.com/documentation/concepts/extending-sails/adapters/available-adapters&#xff09;&#xff0c; 使用时需要在应用程序项目下安装对应的adapter并且在config/datastores或config/env/productio…

Sails的简单学习

这里贴出Sails的官方 一.Sails的简单介绍 官网上说&#xff1a; The web framework of your dreams.你梦想中的web框架。 Sails让创建自定义、企业级的Node.js应用的工作变得简单。它模拟了大家熟悉的诸如Ruby on Rails这种框架的MVC设置模式&#xff0c;但是也拥有满足现代…

什么是Sails

Sails的关键字 Realtime MVC Framework for Node.js Node.js Sails采用纯粹的Node.js进行构建&#xff0c;你只需要掌握一门javascript编程语言就可以构建Sails应用程序&#xff08;Web程序&#xff09;&#xff1b; MVC Framework Sails提供了基于MVC结构组织Web程序的基础…

sublime插件anaconda的设置

在 python 编辑环境下&#xff0c;使用 anaconda 完成一些代码补全和提示 具体设置如下 {//由于Anaconda插件本身无法知道Python安装的路径&#xff0c;所以需要设置Python主程序的实际位置"python_interpreter": "../python.exe",//忽略各种空格不对, 超…

Sublime 插件安装

1、百度搜索 Sublime3&#xff0c;进入 Sublime3 官网下载安装文件 注意&#xff1a;不要走到 Sublime2 的官网去下载&#xff0c;也不要使用 Sublime 的其它中文汉化版本&#xff1b; 2、下载 github 的 Package Control 包&#xff0c;下载地址&#xff1a; https://githu…

Sublime插件安装

1.PackageControl 功能&#xff1a;安装包管理 简介&#xff1a;sublime插件控制台&#xff0c;提供添加、删除、禁用、查找插件等功能 使用&#xff1a;https://sublime.wbond.net/installation 安装方法&#xff1a; CTRL &#xff0c;出现控制台粘贴以下代码至控制台 …

解决sublime无法下载插件问题

解决sublime无法下载插件问题 最近遇到了无法在sublime下载插件的问题&#xff0c;解决方法如下。 首先下载一个文件&#xff0c;地址如下 https://pan.baidu.com/s/1OlC0q8MwiZ_cEbs56SIwzw&#xff0c;提取码为vef9 下载完成后将其解压 再放入sublime文件夹中 接着点开P…

mac sublime安装插件

sublime 安装插件 需要等待一会&#xff0c;在弹出的新窗口&#xff0c;输入要添加的插件的名称&#xff0c;选择确认就可以了 以 Pretty JSON 插件为例&#xff0c;在将json字符串粘贴到文件之后&#xff0c;使用&#xff1a; control command j 进行格式化 调用搜索栏 shi…

java开发sublime插件_开发者最常用的8款Sublime text 3插件

5. SublimeCodeIntel Sublime​Code​Intel 作为一个代码提示和补全插件&#xff0c;支持Javascript、Mason、XBL、XUL、RHTML、SCSS、python、HTML、Ruby、Python3、XML、Sass、XSLT、Django、HTML5、Perl、CSS、Twig、Less、Smarty、Node.js、Tcl、TemplateToolkit 和 PHP 等…

Sublime Text - SublimeREPL插件的配置

1. 菜单Preferences -> Browse Packages&#xff0c;打开安装组件所在的文件夹&#xff0c;进入文件夹Data\Packages\SublimeREPL\config\Python&#xff0c;打开文件Default.sublime-commands&#xff0c;复制如下代码 { "caption": "SublimeREPL: Pyth…

Sublime常用c语言插件

1. Alignment 按等号对齐&#xff0c;强迫症患者必备 Alignment&#xff1a;选中并按ctrlalta就可以使其按照等号对齐 2. 配色方案Enki或者earthbound 3.A file icon 文件图标 4.CoolFormat&#xff1a;C代码格式化 简单好用的代码格式化工具&#xff0c;相当于简化版的Astyl…

Salesforce开发工具Sublime插件(一)

Salesforce开发工具Sublime插件 1. 下载Sublime 3(这是最新) http://www.sublimetext.com/3 进行脑残试的安装方法,下一步即可. 2.装好后打开.exe 3.安装Package Control 这个东东是一个方便 Sublime text 管理插件的插件&#xff0c;这个强大&#xff0c;把它装上去了&#…

关于Sublime的下载与插件安装

Sublime的中文网http://www.sublimetext.cn/ 下载Sublime Sublime的中文网http://www.sublimetext.com/下载Sublime 下载完成 ctrlShiftp 输入install package,确定&#xff0c;此时等待再次出现搜索框&#xff0c;现在就可以下载插件了&#xff0c;现在直接搜索需要的插件名字…