<div class="columns container my-2 mx-1">
<div class="column is-half is-offset-one-quarter">
<h1 class="title">Contribute to Serverless Resources</h1>
<div class="field">
<label class="label" for="url">URL</label>
<div class="control">
<input id="url" name="url" class="input" type="url">
</div>
</div>
<div class="field">
<label class="label" for="tags">Tags (comma separated)</label>
<div class="control">
<input id="tags" class="input" type="text" name="tags">
</div>
</div>
<!-- We'll prepare our javascript's function for later -->
<div class="control">
<button onclick="validateSubmission();" class="button is-link is-fullwidth">Submit</button>
</div>
</div>
</div>
//Helper function to get value by id
function getValue(name) {
return document.getElementById(name).value
}
function validateSubmission() {
const url = getValue('url')
const meta_API = 'https://metadata-api.vercel.app/api?url=' + url
fetch(meta_API)
.then(response => response.json())
.then(function (data) {
let preFilledlink = generateUrl(data.metadata)
window.open(preFilledlink) //redirect with all encoded data
return false
}).catch((error) => {
console.log(error)
});
}
function generateUrl(metadata) {
const title = metadata.title
const description = metadata.description
const author = metadata.author || '' //depend on where author located on the API, fallback empty
const url = getValue('url')
//generate a filename
const filename = title.replace(/\s/g, '-') + ".md"
//Format tags
const tags = getValue('tags')
const formattedTags = '["' + tags.replace(/,/g, '","') + '"]'
//Generate a string mimicing the file structure
//Indentation is important here
let fileText = `---
title: "${title}"
url: "${url}"
author: "${author}"
tags: ${formattedTags}
---
${description}`
//Encode string to URI format
const encodedFileText = encodeURIComponent(fileText)
//Generate a github link with query parameter
const githubQueryLink = "https://github.com/CSS-Tricks/serverless/new/master/src/content/resources/new?value=" + encodedFileText + "&filename=" + filename
return githubQueryLink
}
This Pen doesn't use any external JavaScript resources.