diff --git a/functions/uploadImage/index.js b/functions/uploadImage/index.js new file mode 100644 index 0000000..64ed82a --- /dev/null +++ b/functions/uploadImage/index.js @@ -0,0 +1,30 @@ + + +const AWS = require('aws-sdk'); + +const s3 = new AWS.S3(); + +const v4 = require('uuid').v4; + +function generateUploadParams(content_type, extension, key){ + return { + Bucket: process.env.S3_BUCKET, + Key: `${process.env.NODE_ENV}/${(key) ? key : v4()}${extension}`, + ContentType: content_type, + ACL: 'public-read' + } +} + +module.exports.handler = (event, context, callback) => { + let query = (event.queryStringParameters) ? event.queryStringParameters : event; + let extension = /^\.\w*$/.test(query.extension) ? query.extension : (typeof query.extension != 'undefined') ? `.${query.extension}` : ".undefined"; + let key = (query.key) ? query.key : null; + let content_type = query.content_type; + if (!content_type) return callback(null, {statusCode:400, body: JSON.stringify({message:'please provide a content_type and extension'})}); + s3.getSignedUrl('putObject', generateUploadParams(content_type, extension, key), function (error, url) { + if(error) return callback(null, {statusCode:error.statusCode || 500, body:JSON.stringify({message:error.message})}); + else callback(null, {statusCode:200, body:JSON.stringify({url:url})}); + }); +} + +module.exports.generateUploadParams = generateUploadParams; \ No newline at end of file diff --git a/functions/uploadImage/index.spec.js b/functions/uploadImage/index.spec.js new file mode 100644 index 0000000..655c7b8 --- /dev/null +++ b/functions/uploadImage/index.spec.js @@ -0,0 +1,24 @@ +const { + generateUploadParams, +} = require('./index.js'); + + +describe('uploadImage', () => { + describe('generateUploadParams', () => { + // todo: if event is `{}` promise goes unresolved + // todo: JSON stringify responses + // todo: 'crop' twice in GM_KEYS + + test('should generate correct upload parameters', (done) => { + const expected = { + Bucket: process.env.S3_BUCKET, + Key: `${process.env.NODE_ENV}/test.jpg`, + ContentType: 'image/jpeg', + ACL: 'public-read' + }; + const actual = generateUploadParams('image/jpeg', '.jpg', 'test'); + expect(actual).toEqual(expected); + done(); + }); + }); +}); diff --git a/serverless.yml b/serverless.yml index 35f07e0..745e89c 100644 --- a/serverless.yml +++ b/serverless.yml @@ -35,15 +35,21 @@ functions: - http: GET {proxy+} package: include: - - bin/APIInterface/** - functions/getImage/** resizeImage: name: ${self:provider.environment.RESIZE_LAMBDA} handler: functions/resizeImage/index.handler package: include: - - bin/APIInterface/** - functions/resizeImage/** + uploadImage: + name: ${self:service}-${self:provider.stage}-uploadImage + handler: functions/uploadImage/index.handler + events: + - http: POST /upload + package: + include: + - functions/uploadImage/**