首页 博客 相册 演讲

Serverless 最佳实践之网络请求(中)

2019-11-17

本篇将提供以下问题的解决方案:

原生云函数是通过 Context 中的 headers 来传入 cookie 信息,通过返回 headers 的 set-cookie 来写入 cookie,这种方式显然对于开发者来说不够友好,所以 FaasJS 将其读写操作封装到了 @faasjs/http 插件中,可以通过如下方式来读写 cookie:

import { Func } from '@faasjs/func';
import { Http } from '@faasjs/http';

const http = new Http(); // 创建 http 插件实例

export default new Func({
  plugins: [http], // 将 http 插件实例放到云函数的插件中
  async handler(){
    console.log(http.cookie.read('key')); // 读取 cookie
    http.cookie.write('key', 'value'); // 写入 cookie
  }
});

在 Serverless 中如何存储和使用 Session?

在 Serverless 场景下,每个云函数都是相互独立的,若统一处理 Session 会造成较大的性能损耗。

因此为了使各个云函数能独自处理 Session 信息,推荐将 Session 加密存储于 Cookie 中,并且为了避免 Cookie 信息过多,建议仅存储必须的信息,如 user_id 之类。

Session 使用示例如下:

import { Func } from '@faasjs/func';
import { Http } from '@faasjs/http';

const http = new Http();

export default new Func({
  plugins: [http],
  handler(){
    // 将 session 中的 distinct_id 写入为 user_id
    http.session.write('user_id', http.session.read('distinct_id'));
  }
});

入参校验

随着网络安全变得越来越重要,FaasJS 中也内置了入参校验来避免一些攻击行为。入参校验主要支持以下功能:

代码示例如下:

const http = new Http({
  validator: { // 配置入参校验
    params: { // 校验请求参数
      whitelist: 'error', // 若发现非白名单入参就报错
      rules: { // 每个参数的校验规则
        key: { // 参数名
          required: true, // 必填
          type: 'object', // 参数类型
          config: { // 多层校验
            whitelist: 'error',
            rules: {
              subKey: { // 参数名
                in: [1, 2], // 枚举值校验
                default: 1 // 设定默认值
              }
            }
          }
        }
      }
    }
  }
});

由于入参校验功能支持 Session,因此可以以此来进行简单的鉴权。比如对 Session 中的 user_id 进行必填校验,来判断用户是否已登录。

查看全部文章