Created
July 24, 2023 23:46
-
-
Save CB-Pantomime/afcea14dd868fd61f815cf14250a6c00 to your computer and use it in GitHub Desktop.
Backend PUT Controller for Episode instance with extract src attribute logic
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
| // import statements and other controllers clipped out... | |
| // @desc Update single episode | |
| // @route PUT /api/admin/episodes/:id | |
| // @access Private/Admin Only | |
| // *** TO DO: Add validation and sanitization *** | |
| export const updateEpisode = asyncHandler( async (req, res) => { | |
| let { | |
| title, | |
| subtitle, | |
| linkPodBean, | |
| image, | |
| isReleased | |
| } = req.body; | |
| // Extract the src attribute value from iframe string argument. | |
| // If match is found and there is a captured value, it returns that value. Otherwise returns empty string. | |
| const extractSrcFromIframe = (iframeString) => { | |
| // Regular expression pattern to match the src attribute value in the iframe string. | |
| const srcRegex = /src="([^"]*)"/; | |
| // Use match method to find the src attribute value and store it in the match array. | |
| const match = iframeString.match(srcRegex); | |
| // Check if the match array exists and contains the captured value. | |
| // That captured value we want is at index[1] | |
| if (match && match[1]) { | |
| // Return the captured src attribute value. | |
| return match[1]; | |
| }; | |
| // Return an empty string if no match was found. | |
| return ''; | |
| }; | |
| // Conditionally run the extractSrcFromIframe function to handle cases where the embed code already contains the src attribute. | |
| // If the src attribute is found, it replaces the linkPodBean with the extracted src value, ensuring smooth database entry. | |
| if (linkPodBean.includes('<iframe') || linkPodBean.includes('</iframe>') | |
| || linkPodBean.includes('iframe')) { | |
| const extractedSrc = extractSrcFromIframe(linkPodBean); | |
| if(extractedSrc) { | |
| linkPodBean = extractedSrc; | |
| console.log('extractedSrc: ', linkPodBean) | |
| } else { | |
| console.log('unable to extract src from iframe') | |
| }; | |
| }; | |
| const episode = await Episode.findById(req.params.id); | |
| if(episode) { | |
| episode.title = title | |
| episode.subtitle = subtitle | |
| episode.linkPodBean = linkPodBean | |
| episode.image = image | |
| episode.isReleased = isReleased | |
| const updatedEpisode = await episode.save(); | |
| res.status(201).json(updatedEpisode); | |
| } else { | |
| res.status(404) | |
| throw new Error('Episode not found') | |
| } | |
| }); | |
| // Continued controllers clipped out... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment