{"size": 939, "ext": "js", "max_stars_repo_path": "src/services/buffer.js", "max_stars_repo_name": "cthierer/coral", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/services/buffer.js", "max_issues_repo_name": "cthierer/coral", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/services/buffer.js", "max_forks_repo_name": "cthierer/coral", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 25.3783783784, "max_line_length": 77, "alphanum_fraction": 0.6709265176}
/* eslint-disable import/prefer-default-export */

import fileType from 'file-type'
import uuid from 'uuid'
import { RequestError } from '../errors'

/**
 * @typedef {Object} FileMeta
 * @property {number} size Total size (in bytes) of the file.
 * @property {string} type MIME type of the file.
 * @property {string} name File name for the buffer.
 */

/**
 * Generate file metadata from a file buffer.
 * @param {Buffer} buffer The buffer to extract metadata from.
 * @returns {FileMeta} Extracted file metadata for the provided buffer.
 * @throws {RequestError} If unable to determine the mime type of the upload.
 */
export function getFileMeta(buffer) {
  const { ext, mime } = fileType(buffer) || {}

  if (!ext || !mime) {
    throw new RequestError('unknown file type')
  }

  const id = uuid.v4()
  const fileName = `${id}.${ext}`

  return {
    id,
    size: Buffer.byteLength(buffer),
    type: mime,
    name: fileName,
  }
}
