简体   繁体   中英

nextJS: async getInitialProps() with AWS S3?

I'm trying to get an s3.getObject() running inside an async getInitialProps() function in a nextJS project, but I can't for the love of it figure out how to get the results prepped to they can be returned as an object (which is needed for getInitialProps() and nextJS' SSR to work properly).

Here is the code:

static async getInitialProps({ query }) {
  const AWS = require('aws-sdk');
  const s3 = new AWS.S3({
    credentials: {
      accessKeyId: KEY
      secretAccessKey: KEY
    }
  });

  // The id from the route (e.g. /img/abc123987)
  let filename = query.id;

  const params = {
    Bucket: BUCKETNAME
    Key: KEYDEFAULTS + '/' + filename
  };

  const res = await s3.getObject(params, (err, data) => {
    if (err) throw err;
    let imgData = 'data:image/jpeg;base64,' + data.Body.toString('base64');
    return imgData;
  });

  return ...
}

The idea is to fetch an image from S3 and return it as base64 code (just to clear things up).

From your code, s3.getObject , works with callback. you need to wait for the callback to be called.

You can achieve it by converting this callback into a promise.


static async getInitialProps({ query }) {
  const AWS = require('aws-sdk');
  const s3 = new AWS.S3({
    credentials: {
      accessKeyId: KEY
      secretAccessKey: KEY
    }
  });

  // The id from the route (e.g. /img/abc123987)
  let filename = query.id;

  const params = {
    Bucket: BUCKETNAME
    Key: KEYDEFAULTS + '/' + filename
  };

  const res = await new Promise((resolve, reject) => {
    s3.getObject(params, (err, data) => {
      if (err) reject(err);
      let imgData = 'data:image/jpeg;base64,' + data.Body.toString('base64');
      resolve(imgData);
    });
  });


  return ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM