{"size": 2062, "ext": "js", "max_stars_repo_path": "functions/aircraft/addAttachments.js", "max_stars_repo_name": "odch/aircraft-logbook", "max_stars_repo_stars_event_min_datetime": "2021-02-12T15:47:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-12T15:47:50.000Z", "max_issues_repo_path": "functions/aircraft/addAttachments.js", "max_issues_repo_name": "weblate/aircraft-logbook", "max_issues_repo_issues_event_min_datetime": "2018-08-26T09:06:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T09:59:33.000Z", "max_forks_repo_path": "functions/aircraft/addAttachments.js", "max_forks_repo_name": "weblate/aircraft-logbook", "max_forks_repo_forks_event_min_datetime": "2019-02-06T11:11:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-13T11:37:12.000Z"}
{"max_stars_count": 1, "max_issues_count": 178, "max_forks_count": 2, "avg_line_length": 21.2577319588, "max_line_length": 87, "alphanum_fraction": 0.6096023278}
const uuid = require('uuid')
const stream = require('stream')

const writeFile = (attachment, file) =>
  new Promise((resolve, reject) => {
    const { name, base64, contentType } = attachment

    const bufferStream = new stream.PassThrough()
    bufferStream.end(Buffer.from(base64, 'base64'))

    bufferStream
      .pipe(
        file.createWriteStream({
          metadata: {
            contentType,
            metadata: {
              originalName: name
            }
          }
        })
      )
      .on('error', e => reject(e))
      .on('finish', () => resolve())
  })

const getPath = (organizationId, aircraftId, techlogEntryId, actionId, name) =>
  `organizations/${organizationId}/aircrafts/${aircraftId}/techlog/${techlogEntryId}/${
    actionId ? `${actionId}/` : ''
  }${name}`

const addAttachment = async (
  bucket,
  organizationId,
  aircraftId,
  techlogEntryId,
  actionId,
  attachment
) => {
  const id = uuid.v4()
  const extension = attachment.name.split('.').pop()
  const name = id + '.' + extension
  const path = getPath(
    organizationId,
    aircraftId,
    techlogEntryId,
    actionId,
    name
  )

  const file = bucket.file(path)
  await writeFile(attachment, file)

  const [metadata] = await file.getMetadata()

  return {
    file,
    name,
    metadata,
    originalName: attachment.name
  }
}

const addAttachments = async (
  bucket,
  organizationId,
  aircraftId,
  techlogEntryId,
  actionId,
  attachments
) => {
  if (!attachments || attachments.length === 0) {
    return []
  }
  const results = await Promise.all(
    attachments.map(
      async attachment =>
        await addAttachment(
          bucket,
          organizationId,
          aircraftId,
          techlogEntryId,
          actionId,
          attachment
        )
    )
  )
  return results.map(result => ({
    name: result.name,
    originalName: result.originalName,
    size: parseInt(result.metadata.size),
    contentType: result.metadata.contentType,
    path: result.metadata.name
  }))
}

module.exports = addAttachments
