カテゴリー
CodeGenieApp/serverless-express(Express Adapter for AWS)のv4への更新方法
※ 当ページには【広告/PR】を含む場合があります。
2024/08/18
3系から4系への手動更新
Lambdaハンドラーの修正点
const awsServerlessExpress = require('aws-serverless-express')
const app = require('./app')
const binaryMimeTypes = [
'image/*'
]
const server = awsServerlessExpress.createServer(app, null, binaryMimeTypes)
exports.handler = (event, context) => {
awsServerlessExpress.proxy(server, event, context)
}
const serverlessExpress = require('@codegenie/serverless-express');
const app = require('./app');
exports.handler = serverlessExpress({ app });
binaryMimeTypes
serverlessExpress
binarySettings
serverlessExpress({
app,
binarySettings: {
isBinary: ({ headers }) => true,
contentTypes: [],
contentEncodings: []
}
})
Lambda event/contextを受け取る場合の修正点
event
context
awsServerlessExpressMiddleware
const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware');
router.use(awsServerlessExpressMiddleware.eventContext());
router.get('/', (req, res) => {
res.json({
stage: req.apiGateway.event.requestContext.stage
})
})
getCurrentInvoke
event
context
const { getCurrentInvoke } = require('@codegenie/serverless-express');
router.get('/', (req, res) => {
const currentInvoke = getCurrentInvoke();
res.json({
stage: currentInvoke.event.requestContext.stage
})
})
Angular Universal(旧Angular/SSR)とSeeverless Framework(v3)の組み合わせを修正
3系のアダプターの場合
lambda.js
const awsServerlessExpress = require('aws-serverless-express');
const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware');
//👇MIMEの指定は必須
const binaryMimeTypes = [
'application/javascript',
'application/json',
'application/octet-stream',
'application/xml',
'image/jpeg',
'image/png',
'image/gif',
'text/comma-separated-values',
'text/css',
'text/html',
'text/javascript',
'text/plain',
'text/text',
'text/xml',
'image/x-icon',
'image/svg+xml',
'application/x-font-ttf'
];
module.exports.universal = async (event, context) => {
try {
//👇ESModule対応でビルド済みのExpressサーバーをインポート
const server = await import('./dist/my-app/server/server.mjs');
const app = await server.app();
app.use(awsServerlessExpressMiddleware.eventContext());
const serverAws = awsServerlessExpress.createServer(app, null, binaryMimeTypes);
if (!app) {
console.error('Server is not initialized');
return;
}
else {
return awsServerlessExpress.proxy(serverAws, event, context, 'PROMISE').promise;
}
} catch (error) {
console.error('Failed to import app:', error);
}
};
serverless.yml
service: <デプロイ先のアプリ名>
frameworkVersion: "3"
plugins:
- serverless-apigw-binary
- serverless-domain-manager
provider:
name: aws
runtime: nodejs20.x
memorySize: 192
timeout: 10
stage: ${opt:stage,"dev"}
region: ap-northeast-1
apiGateway:
disableDefaultEndpoint: true
package:
patterns:
- '!**'
- 'dist/**'
- 'lambda.js'
- 'node_modules/@vendia/**'
- 'node_modules/aws-serverless-express/**'
- 'node_modules/@codegenie/**'
- "node_modules/@angular/ssr"
- 'node_modules/binary-case/**'
- 'node_modules/type-is/**'
- 'node_modules/media-typer/**'
- 'node_modules/mime-types/**'
- 'node_modules/mime-db/**'
custom:
apigwBinary:
types:
- '*/*'
customDomains:
- rest:
domainName: '<カスタムドメイン名>'
basePath: ''
stage: ${self:provider.stage}
createRoute53Record: true
functions:
api:
handler: lambda.universal
events:
- http:
path: /
method: GET
cors:
origin: '*'
headers:
- Content-Type
- X-Amz-Date
- Authorization
- X-Api-Key
- X-Amz-Security-Token
- X-Amz-User-Agent
allowCredentials: false
- http:
path: /{proxy+}
method: GET
cors:
origin: '*'
headers:
- Content-Type
- X-Amz-Date
- Authorization
- X-Api-Key
- X-Amz-Security-Token
- X-Amz-User-Agent
allowCredentials: false
$ serverless deploy --verbose
4系へ移行する場合
const serverlessExpress = require('@codegenie/serverless-express');
module.exports.universal = async (event, context) => {
try {
const server = await import('./dist/my-app/server/server.mjs');
const app = await server.app();
if (!app) {
console.error('Server is not initialized');
return;
} else {
const cachedServerlessExpress = serverlessExpress({ app });
return cachedServerlessExpress(event, context);
}
} catch (error) {
console.error('Failed to import app:', error);
}
};
serverless.yml
package
#...中略
package:
patterns:
- '!**'
- 'dist/**'
- 'lambda.js'
- 'node_modules/@codegenie/**'
- "node_modules/@angular/ssr"
#...以下略
まとめ
記事を書いた人
ナンデモ系エンジニア
主にAngularでフロントエンド開発することが多いです。 開発環境はLinuxメインで進めているので、シェルコマンドも多用しております。 コツコツとプログラミングするのが好きな人間です。
カテゴリー