LoginSignup
0
0

More than 3 years have passed since last update.

AWSLambda(Node.js)の入力パラメータチェック

Last updated at Posted at 2020-09-07

AWSLambda(Node.js)のREST APIにおいて入力パラメータのチェックがしたい
そうだ、value-schemaを使おう

value-schemaができること

1.必須パラメータの有無、
2.型、
3.想定範囲内に存在するか(e.g.limit < input < limit)、
上記3点における入力パラメータの検証と修正ができる

使い方

大きく2つの書き方がある....と勝手に思ってる
基本のフォーマットは vs.型名( {オプション} )

//====その1. オブジェクトの中身をまとめてチェックする方法====
var vs = require("value-schema");

// 入力パラメータのオブジェクト
let requestbody = {
    testId: "test",
    testNum: 1,
    testlist: [1, 2, 3],
    NoCheckid:"no",
};

// 入力パラメータの満たすべき条件
const schemaObject = {
    testId: vs.string({minLength: 3}), //eventIdが文字列かつ5文字以上
    testNum: vs.number({minValue: 1,}), //testNumが数字かつ1以上
    testlist: vs.array({minLength: 2}), //testlistがarrayかつ2要素以上
                                        //noNoCheckidは条件を書いてないのでチェックされない
};

// 全ての条件を満たさない場合エラーを投げる,満たす場合は変数にいれる
const checkedRequestbody = vs.applySchemaObject(schemaObject,requestbody,(err)=> {
    throw new Error("入力パラメータがおかしい")
});
//====その2. パラメータ単体でチェックする方法====
var vs = require("value-schema");
const flag = true;
const checkedName = vs.boolean().applyTo(flag,(err)=> { //flagがbool値である
    throw new Error("入力flagがおかしい") //条件を見たさない場合err投げる
});

ほぼ全ての型で使える便利なオプション

{strictType: true} : 厳密なタイプチェックができる、デフォルトはオフ
{ifUndefined: somevalue} : パラメータがundefinedの場合に任意の値を入れておく
{ifNull: somevalue} : パラメータがnullの場合に任意の値を入れておく
{ifEmptyString: somevalue} : パラメータが空文字""の場合に任意の値を入れておく

*その他オプションなどは公式を参照

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0