Sunday, 4 June 2017

getModel() is not defined - but it was defined

I am creating file upload functionality on Cloud Storage. Here's the backend code:

const Storage = require('@google-cloud/storage')
const storage = Storage({
    projectId: 'a-1485'
})

const bucket = storage.bucket('a-1485.appspot.com')
function getPublicUrl (filename) {
  return 'https://storage.googleapis.com/a-1485.appspot.com/${filename}'
}

function sendUploadToGCS (req, res, next) {
  if (!req.file) {
    return next()
  }

  const gcsname = Date.now() + req.file.originalname
  console.log(gcsname)
  const file = bucket.file(gcsname)

  const stream = file.createWriteStream({
    metadata: {
      contentType: req.file.mimetype
    }
  })

  stream.on('error', (err) => {
    req.file.cloudStorageError = err
    next(err)
  })

  stream.on('finish', () => {
    req.file.cloudStorageObject = gcsname
    req.file.cloudStoragePublicUrl = getPublicUrl(gcsname)
    next()
  })

  stream.end(req.file.buffer);
}

module.exports = {
  getPublicUrl,
  sendUploadToGCS
}

In my app.js file:

app.post('/upload-image', multer.single('image'), images.sendUploadToGCS, (req, res, next) => {
  let data = req.body
  console.log(data)
  if (req.file && req.file.cloudStoragePublicUrl) {
    data.imageUrl = req.file.cloudStoragePublicUrl
  }

  getModel().create(data, (err, savedData) => {
    if (err) {
      next(err)
      return
    }
    res.redirect(`${req.baseUrl}/${savedData.id}`);
  })
}
)

However, when I upload an image I get an error thrown saying 'getModel()' is not defined. But as you can see above it is defined. What is the problem?



via konyv12

No comments:

Post a Comment