LoginSignup
3
1

More than 5 years have passed since last update.

SwaggerでLambdaのデバッグ環境を作る(2):Helperライブラリを使ったLambdaの書き方

Last updated at Posted at 2019-02-05

前回、SwaggerでLambdaのデバッグ環境を作りました。

 SwaggerでLambdaのデバッグ環境を作る(1)

入力パラメータの受け取り方を示しておきます。
また、Helperライブラリを作っていましたので、その使い方も補足しておきます。

入力パラメータ

GET呼び出しで取得するQueryStringは、以下のように受け取ります。

var qs = event.queryStringParameters;

POST呼び出しで取得するBody部は、以下のように受け取ります。JSONである前提です。

var body = JSON.parse(event.body);

(参考)
https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format

response.js

これは、JSON形式でレスポンスを返すのに有用なライブラリです。

例えば、以下のようにすると、引数にしたオブジェクトがJSON形式でクライアントに返されます。

定義。

const HELPER_BASE = process.env.HELPER_BASE || '../../helpers/';
const Response = require(HELPER_BASE + 'response');

使い方。

return new Response({ message : 'Hello World' });

または、

var body = { message : 'Hello World' };
var response = new Response();
response.statusCode = 200;
response.set_body(body);
return response;

(参考)
https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-output-format

ちなみに、クライアントへJSONを返す方法として以下の方法があります。

// ①
exports.handler = async (event, context, callback) => {
    return new Response({ message: 'Hello World' });
};

// ②
exports.handler = async (event, context, callback) => {
    callback(null, new Response({ message: 'Hello World' }) );
};

// ③
exports.handler = async (event, context, callback) => {
    context.succeed( new Response({ message: 'Hello World' } );
};

通常は、①か②の方法が使われるかと思います。ただし、①はexport.handlerにasyncを付けた場合だけ使うことができます。

(参考)
https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/nodejs-prog-model-handler.html

redirect.js

これは、クライアント側の表示ページを別のページに切り替えたい場合(リダイレクト)に使います。

定義。

const HELPER_BASE = process.env.HELPER_BASE || '../../helpers/';
const Redirect = require(HELPER_BASE + 'redirect');

response.jsの代わりに、以下のように使います。

使い方。

exports.handler = async (event, context, callback) => {
    return new Redirect('https://www.google.com');
};

以上

3
1
1

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
3
1