Created
December 24, 2021 19:13
-
-
Save albertBarsegyan/7676fa426fce05f3af6f209b8f87054f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable */ | |
import { Octokit } from '@octokit/rest'; | |
import { popupMessages } from '../../constants/popup-messages.constants'; | |
import { popupVariants } from '../../constants/popup.constants'; | |
import { getUserNameFromEmail } from '../../helpers/string.helpers'; | |
import { | |
GithubOrganization, | |
successStatusCodes, | |
} from './constants/github.constants'; | |
import { getPostCommitMessage } from './handleData'; | |
const octokit = new Octokit({ | |
auth: process.env.NEXT_PUBLIC_GITHUB_TOKEN, | |
}); | |
export default async function handleImage(req, res) { | |
let existingFile = null; | |
let message; | |
const { imageName, committer, imageContent, imagePath } = req.body; | |
const userName = getUserNameFromEmail(committer); | |
try { | |
existingFile = await octokit.request( | |
'GET /repos/{owner}/{repo}/contents/{path}', | |
{ | |
headers: { | |
accept: 'application/vnd.github.v3+json', | |
}, | |
owner: GithubOrganization.name, | |
repo: GithubOrganization.repo, | |
path: imagePath, | |
ref: GithubOrganization.defaultBranch, | |
}, | |
); | |
} catch (e) { | |
message = `Uploaded new image by ${committer}`; | |
} | |
try { | |
const buffer = Buffer.from(imageContent, 'binary'); | |
const base64Data = Buffer.from(buffer).toString('base64'); | |
const response = await octokit.repos.createOrUpdateFileContents({ | |
owner: GithubOrganization.name, | |
repo: GithubOrganization.repo, | |
sha: existingFile?.data?.sha, | |
branch: GithubOrganization.defaultBranch, | |
path: imagePath, | |
content: base64Data, | |
message: getPostCommitMessage(imageName, !existingFile), | |
committer: { name: userName, email: committer }, | |
}); | |
if (successStatusCodes.includes(response.status)) { | |
res.json({ | |
variant: popupVariants.success, | |
message: message ?? popupMessages.successImageUpload(), | |
}); | |
} | |
throw new Error('Something was wrong.'); | |
} catch (e) { | |
res.json({ variant: popupVariants.danger, message: e.message }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment