├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── image_event.json ├── package.json └── thumb_src.js /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | 5 | # Runtime data 6 | pids 7 | *.pid 8 | *.seed 9 | 10 | # Directory for instrumented libs generated by jscoverage/JSCover 11 | lib-cov 12 | 13 | # Coverage directory used by tools like istanbul 14 | coverage 15 | 16 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 17 | .grunt 18 | 19 | # node-waf configuration 20 | .lock-wscript 21 | 22 | # Compiled binary addons (http://nodejs.org/api/addons.html) 23 | build/Release 24 | 25 | # Dependency directory 26 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git 27 | node_modules 28 | thumb.js 29 | thumb.zip 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Tyr Chen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | CMD=aws lambda 2 | CREATE_CMD=create-function 3 | DELETE_CMD=delete-function 4 | UPDATE_CMD=update-function-code 5 | UPDATE_CONFIG_CMD=update-function-configuration 6 | TEST_CMD=invoke-async 7 | TEST_EVENT=image_event.json 8 | 9 | PROFILE=$(AWSP) # if you want to use a different profile, set env variable AWSP=--profile 10 | FUNC_NAME=--function-name thumbnail 11 | TIMEOUT=60 12 | 13 | HANDLER=thumb 14 | SRC_FILE=$(HANDLER)_src.js 15 | ZIP_FILE=$(HANDLER).zip 16 | HANDLER_FILE=$(HANDLER).js 17 | NODE_MODULES=node_modules 18 | 19 | deploy: zip 20 | $(CMD) $(UPDATE_CMD) $(FUNC_NAME) $(PROFILE) --zip-file fileb://$(ZIP_FILE) 21 | 22 | update: 23 | $(CMD) $(UPDATE_CONFIG_CMD) $(FUNC_NAME) $(PROFILE) --timeout 60 24 | 25 | test: 26 | $(CMD) $(TEST_CMD) $(FUNC_NAME) $(PROFILE) --invoke-args $(TEST_EVENT) --debug 27 | 28 | zip: 29 | @rm -f $(ZIP_FILE) 30 | @babel $(SRC_FILE) > $(HANDLER_FILE) 31 | @zip -r $(ZIP_FILE) $(NODE_MODULES) $(HANDLER_FILE) 32 | 33 | create: zip 34 | $(CMD) $(CREATE_CMD) $(FUNC_NAME) $(PROFILE) \ 35 | --zip-file fileb://$(ZIP_FILE) \ 36 | --role $(LAMBDA_ROLE) \ 37 | --handler $(HANDLER).handler \ 38 | --runtime nodejs \ 39 | --timeout $(TIMEOUT) \ 40 | --debug \ 41 | # arn:aws:s3 is not supported by cli yet 42 | #$(CMD) $(CREATE_EVENT_SRC_CMD) $(FUNC_NAME) $(PROFILE) \ 43 | --event-source-arn arn:aws:s3:::tchen-lambda --enabled \ 44 | --starting-position LATEST 45 | 46 | delete: 47 | $(CMD) $(DELETE_CMD) $(FUNC_NAME) $(PROFILE) 48 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # aws-lambda-thumbnail 2 | Example code to show aws lambda event driven functionality 3 | -------------------------------------------------------------------------------- /image_event.json: -------------------------------------------------------------------------------- 1 | { 2 | "Records": [ 3 | { 4 | "eventVersion": "2.0", 5 | "eventTime": "1970-01-01T00:00:00.000Z", 6 | "requestParameters": { 7 | "sourceIPAddress": "127.0.0.1" 8 | }, 9 | "s3": { 10 | "configurationId": "testConfigRule", 11 | "object": { 12 | "eTag": "0123456789abcdef0123456789abcdef", 13 | "sequencer": "0A1B2C3D4E5F678901", 14 | "key": "images/1.pic.jpg", 15 | "size": 59000 16 | }, 17 | "bucket": { 18 | "arn": "arn:aws:s3:::tchen-lambda", 19 | "name": "tchen-lambda", 20 | "ownerIdentity": { 21 | "principalId": "EXAMPLE" 22 | } 23 | }, 24 | "s3SchemaVersion": "1.0" 25 | }, 26 | "responseElements": { 27 | "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH", 28 | "x-amz-request-id": "EXAMPLE123456789" 29 | }, 30 | "awsRegion": "us-west-2", 31 | "eventName": "ObjectCreated:Put", 32 | "userIdentity": { 33 | "principalId": "EXAMPLE" 34 | }, 35 | "eventSource": "aws:s3" 36 | } 37 | ] 38 | } 39 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "sam", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "Tyr Chen (http://tchen.me)", 10 | "license": "ISC", 11 | "dependencies": { 12 | "bluebird": "^2.10.2", 13 | "gm": "^1.20.0" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /thumb_src.js: -------------------------------------------------------------------------------- 1 | const AWS = require('aws-sdk') 2 | const gm = require('gm').subClass({imageMagick: true}) 3 | const Promise = require('bluebird') 4 | const util = require('util') 5 | 6 | const MAX_WIDTH = 100 7 | const MAX_HEIGHT = 100 8 | 9 | const S3 = Promise.promisifyAll(new AWS.S3()) 10 | 11 | function resize_image(context, bucket, key, newKey, imageType) { 12 | console.log(bucket, key, newKey, imageType); 13 | S3.getObjectAsync({ 14 | Bucket: bucket, 15 | Key: key 16 | }).then(response => { 17 | console.log(response.ContentType) 18 | return new Promise((res, rej) => { 19 | gm(response.Body).size(function(err, size) { 20 | const scalingFactor = Math.min(MAX_WIDTH / size.width, MAX_HEIGHT / size.height) 21 | const width = scalingFactor * size.width 22 | const height = scalingFactor * size.height 23 | const self = this; 24 | self.resize(width, height).toBuffer(imageType, (err, buffer) => { 25 | if (err) { 26 | rej(err); 27 | } else { 28 | console.log(buffer) 29 | res({contentType: response.ContentType, data: buffer}); 30 | } 31 | }) 32 | }) 33 | }) 34 | }).then(response => S3.putObjectAsync({ 35 | Bucket: bucket, 36 | Key: newKey, 37 | Body: response.data, 38 | ContentType: response.contentType 39 | })).then(info => { 40 | console.log('succeeded!', info) 41 | context.done() 42 | }).catch(err => { 43 | if (err) { 44 | console.error(`unable to resize ${bucket}/${key} and upload to ${bucket}/${newKey}, err:`, err) 45 | } 46 | }) 47 | } 48 | 49 | export function handler(event, context) { 50 | console.log('Reading options from event:\n', util.inspect(event, {depth: 5})) 51 | const e = event.Records[0].s3 52 | const bucket = e.bucket.name 53 | const srcKey = decodeURIComponent(e.object.key.replace(/\+/g, ' ')) 54 | const dstKey = srcKey.replace(/^images/, 'thumbnails') 55 | console.log(`srcKey: ${srcKey}, dstKey: ${dstKey}`) 56 | const typeMatch = srcKey.match(/\.([^.]*)$/) 57 | if (!typeMatch) { 58 | console.error(`unable to infer image type for key ${srcKey}`) 59 | return 60 | } 61 | 62 | const imageType = typeMatch[1]; 63 | if (imageType != 'jpg' && imageType != 'png') { 64 | console.log(`skipping non-image ${srcKey}`) 65 | return 66 | } 67 | resize_image(context, bucket, srcKey, dstKey, imageType) 68 | } 69 | --------------------------------------------------------------------------------