Created
December 24, 2021 19:01
-
-
Save albertBarsegyan/59849275b25c6cb628efd2426eb2d144 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 path from 'path'; | |
| import { Languages } from '../../constants'; | |
| import { popupMessages } from '../../constants/popup-messages.constants'; | |
| import { popupVariants } from '../../constants/popup.constants'; | |
| import { getUserNameFromEmail } from '../../helpers/string.helpers'; | |
| import { octokit } from '../../services/admin.services'; | |
| import { GithubOrganization } from './constants/github.constants'; | |
| export const getPostCommitMessage = (postName, isNewFile) => | |
| `feat(${postName}): ${postName} is ${isNewFile ? 'created' : 'updated'}!`; | |
| const PostFileInfo = { | |
| fileExtension: 'json', | |
| getPathToFile: (lang = Languages.en) => `public/static/locales/${lang}`, | |
| }; | |
| export default async function handleData(req, res) { | |
| let existingFile = null; | |
| const { fileToUpdate, committer, content, lang, contentType } = req.body; | |
| let message = popupMessages.submitSuccessMessage(contentType); | |
| const userName = getUserNameFromEmail(committer); | |
| const fullPath = `${PostFileInfo.getPathToFile(lang)}/${fileToUpdate}.${ | |
| PostFileInfo.fileExtension | |
| }`; | |
| 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: fullPath, | |
| ref: GithubOrganization.defaultBranch, | |
| }, | |
| ); | |
| } catch (e) { | |
| message = `Created new ${contentType} by ${committer}`; | |
| } | |
| try { | |
| const objJsonStr = JSON.stringify(content, null, 2); | |
| const objJsonB64 = Buffer.from(objJsonStr).toString('base64'); | |
| const response = await octokit.repos.createOrUpdateFileContents({ | |
| owner: GithubOrganization.name, | |
| repo: GithubOrganization.repo, | |
| sha: existingFile?.data?.sha, | |
| branch: GithubOrganization.defaultBranch, | |
| path: fullPath, | |
| content: objJsonB64, | |
| message: getPostCommitMessage(fileToUpdate, !existingFile), | |
| committer: { name: userName, email: committer }, | |
| }); | |
| res.status(response.status).json({ | |
| variant: popupVariants.success, | |
| message, | |
| }); | |
| } catch (e) { | |
| res.status(500).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