UNPKG

s3getimage

Version:

function for checking existence of image fie on s3 and return the presigned url

58 lines (48 loc) 1.67 kB
'use strict'; console.log('Starting s3GetImage'); /** import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; import { S3Client } from "@aws-sdk/client-s3"; import { GetObjectCommand } from "@aws-sdk/client-s3"; import {ListObjectsV2Command } from "@aws-sdk/client-s3"; */ const{ getSignedUrl } = require("@aws-sdk/s3-request-presigner"); const { S3Client } = require("@aws-sdk/client-s3"); const { GetObjectCommand } = require("@aws-sdk/client-s3"); const { ListObjectsV2Command } = require("@aws-sdk/client-s3"); const client = new S3Client({ region: "eu-central-1" }); async function s3getimage(event) { console.log('Event: ' + JSON.stringify(event)); var s3Bucket = event.s3bucket; const params = { Bucket: s3Bucket, Prefix: event.userid } const command = new ListObjectsV2Command(params); try { const objectList = await client.send(command); if (objectList.Contents.length < 1) { console.log('there are no images with this key: ' + JSON.stringify(objectList.Contents.length)); } else { let imgKey = objectList.Contents[0].Key; console.log('Image Key: ' + JSON.stringify(imgKey)); const params = { Bucket: s3Bucket, Key: imgKey, Expires: event.expiry }; const command = new GetObjectCommand(params); try { const objectUrl = await getSignedUrl(client, command); return objectUrl; } catch (err) { console.log('Signed URL: ' +err.statusCode + 'No user image found'); } } } catch (err) { console.log('List objects: ' + err.statusCode + ' No user image found'); } } module.exports = { s3getimage };