Advertisement
bheng8200

device-icon-s3.js

Jun 25th, 2021
1,179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. deviceIcon.getImage = async(req, res, next) => {
  2.     try {
  3.  
  4.         if (!req.body.deviceName) {
  5.             res.status(400).json({msg: 'Device name required'});
  6.             return;
  7.         }
  8.  
  9.         AWS.config.update({
  10.             apiVersion: '2006-03-01',
  11.             accessKeyId: config.aws.accessKeyId,
  12.             secretAccessKey: config.aws.secretAccessKey
  13.         });
  14.  
  15.         const s3 = new AWS.S3();
  16.  
  17.         if (!s3) {
  18.             res.status(500).json({msg: 'Can\'t Initialize S3 Object - Check your AWS settings in your .env'});
  19.             return;
  20.         }
  21.      
  22.         const deviceName = req.body.deviceName.replace(/[^0-9a-z]/gi, '').toLowerCase();
  23.  
  24.         s3.listObjectsV2({Bucket: config.aws.s3BucketName}, (err, data) => {
  25.             if (err) {
  26.                 console.error(err);
  27.                 res.status(500).json({msg: 'Internal server error'}).end();
  28.             } else {
  29.                
  30.                 const files = data.Contents.map(file => ({
  31.                     filename: file.Key.split('.').slice(0, -1).join('.'),
  32.                     uri: config.aws.url + file.Key,
  33.                     similarity: stringSimilarity.compareTwoStrings(deviceName, file.Key.split('.').slice(0, -1).join('.').split('-').join(' ').toLowerCase())
  34.                 }));
  35.  
  36.                 let maxS = 0;
  37.                 let result = null;
  38.  
  39.                 for (const file of files) {
  40.                     if (file.similarity > maxS) {
  41.                         maxS = file.similarity;
  42.                         result = file;
  43.                     }
  44.                 }
  45.  
  46.                 if (result && result.similarity > 0.50) {
  47.                     res.status(200).json({icon: result.uri}).end();
  48.                 } else {
  49.                     res.status(200).json({icon: config.aws.url + 'no-img.png'}).end();
  50.                 }
  51.             }
  52.         });
  53.  
  54.     } catch (error) {
  55.         next(error);
  56.     }
  57. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement