44
loading...
This website collects cookies to deliver better user experience
This is might be a given, but be sure to clone your code and not edit the original one,
It may not affect but it's makes for freedom to edit to satisfaction
$ npm install -g serverless
$ cd your-project-directory
$ npm install --save serverless
serverless
& sls
. sls
is an alias to serverless
$ sls create --template aws-nodejs --name <custom-unique-name>
.
├── .npmignore
├── handler.js
└── serverless.yml
'use strict';
module.exports.hello = async (event) => {
return {
statusCode: 200,
body: JSON.stringify(
{
message: 'Go Serverless v1.0! Your function executed successfully!',
input: event,
},
null,
2
),
};
// Use this code if you don't use the http event with the LAMBDA-PROXY integration
// return { message: 'Go Serverless v1.0! Your function executed successfully!', event };
};
provider:
name: aws
runtime: nodejs12.x
lambdaHashingVersion: 20201221
stage: dev
region: us-west-1
...
--name
flag we specified when adding adding serverless)
functions:
hello:
handler: handler.hello
...
resources:
Resources:
NewResource:
Type: AWS::S3::Bucket
Properties:
BucketName: my-new-bucket
Outputs:
NewOutput:
Description: "Description for the output"
Value: "Some output value"
I won't bore you with the details, you can update it as shown below. It should work for your application too
service: <autogenerated> # Service name (must be unique for your account, no two services can share the same name)
frameworkVersion: "2" # Recommended to pin it to a working version so updates won't break your application
provider:
name: aws # Name of the cloud provider
runtime: nodejs14.x # node runtime that the deploy will work on, this is different from the nodejs version required for sls to run
lambdaHashingVersion: 20201221 # Recommended (honestly, no idea why. Lemme know in the comments what it means)
memorySize: 130 # Memory size required for lambda functions to run
timeout: 10 # 10s timeout for a request to be cancelled
stage: {opt:stage, 'dev'} # Stage to run the functions, it is used for development process to specify which ENV to run
region: eu-west-1 # Optional override, it will be automatically set from AWS
functions:
api: # can be any name, this will be mapped to the functions on lambda. It has to be unique
handler: handler.api # The file.exportedFunction that the functions will be use when the event is created
events:
- http: ANY / # RegExps all the HTTP Routes GET|POST|PUT|PATCH|DELETE|OPTIONS, etc.
- http: ANY /{proxy+} # If your routes use queries and parameters
Oh look, I ended up adding the details. Make sure to remove the comments.
npm install aws-lambda-fastify
handler.js
using your editor and update it as followsconst awsLambdaFastify = require('aws-lambda-fastify');
const app = require('./app');
const proxy = awsLambdaFastify(app);
exports.api = (event, context) => proxy(event, context);
app.js
and update itconst fastify = require('fastify');
const cors = require('fastify-cors');
const mongoose = require('mongoose');
require('dotenv').config();
const controllers = require('./controllers');
const MONGO_URI = process.env.MONGO_URI || 'mongodb://localhost:27017/movie';
const PORT = process.env.PORT || 3000;
// Connect to the db
mongoose
.connect(MONGO_URI, {
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then((connection) => {
console.log(`Database connected ::: ${connection.connection.host}`);
})
.catch((err) => {
console.error(`Error ::: ${err.message}`);
process.exit();
});
// Initialize app
const app = fastify();
// CORS
app.register(cors, {
origin: '*',
});
// Routes
app.get('/', controllers.getAll);
app.post('/create', controllers.create);
app.get('/:id', controllers.getOne);
app.put('/:id/update', controllers.updateOne);
app.delete('/:id/delete', controllers.deleteOne);
// Run as backend server if the file is called directly
if (require.main === module) {
app.listen(PORT, (err) => {
if (err) console.error(err);
console.log(`server running on ${PORT}`);
});
} else {
// Execute as aws lambda function when required as a module
module.exports = app;
}
// Run as backend server if the file is called directly
if (require.main === module) {
app.listen(PORT, (err) => {
if (err) console.error(err);
console.log(`server running on ${PORT}`);
});
} else {
// Execute as aws lambda function when required as a module
module.exports = app;
}
node app.js
and runs it as a function when imported from our handler.js
filecontrollers.js
filereq,res
with event
since our requests are now events but it works the same. Fastify Power!// const create = async (req,res) {
const create = async (event) => {
try {
const newMovie = await Movie.create(event.body); // Events are sent in JSON format
return {
statuCode: 201,
body: JSON.stringify(
{
message: 'new movie created',
newMovie,
},
null,
2
),
};
} catch (err) {
return {
statuCode: err.code || 500,
message: JSON.stringify(err),
};
}
};
...
Explanation Time!: Serverless Offline is a Serverless plugin that emulates AWS and API Gateway on your local machine to speed up your development cycles. - Serverless
npm install --save-dev serverless-offline
serverless.yml
file...
plugins:
- serverless-offline
sls offline start
sls deploy
PS: I couldn't deploy mine, for some reason, I can't access my AWS account, story for later.