Search code examples
javascriptreactjsgithubnetlifynetlify-function

How to create a md file using javascript data onto github


I'm getting form submission data through Netlify forms.

I want to be able to create a md file with that same data on github when the form is submitted.

So far on my submission-created.js function (triggered by client submission) I'm fetching client's submission data like so:

exports.handler = async function(event, context, callback) {

  const data = JSON.parse(event.body).payload.data;

  let date = new Date().toUTCString().replace(/[\s|,|:]/g, "-");
  date = date.substring(5, date.length);

  let courtData = 
`---
name: Automatic-file-${date}
location:
lat: ${data?.latitude}
lng: ${data?.longitude}
email: ${data?.email}
byhoopers: ${data?.byhoopers ? data?.byhoopers : false}
openUse: ${data?.openUse}
openTime: ${data?.openTime ? data?.openTime : "unknown"}
social: ${data?.social}
image: ${data?.file?.url}
formcourt: true
---
${data?.info ? data?.info : ""}
![](${data?.file2?.url ? data?.file2?.url : ""})
![](${data?.file3?.url ? data?.file3?.url : ""})
![](${data?.file4?.url ? data?.file4?.url : ""})
![](${data?.file5?.url ? data?.file5?.url : ""})
`;

  return { 
    statusCode: 200,
    body: JSON.stringify(data),
  };
};

It's working fine but now I need to save this data to a md file and push it to github.

I'm doing something like this but struggling with next step:

let githubContent = Buffer.from(courtData).toString('base64');

let courtInfo = JSON.stringify({
    message: `new court file ${date}`,
    content: githubContent,
});

let githubPush = {
        method: "put",
        url: `https://api.github.com/repos/*****${date}.md`,

    headers: {
        Authorization: "*********",
        "Content-Type": "application/json",
    },
    data: courtInfo,
};

Solution

  • Axios did the job like so:

    await axios(githubPush)
        .then(function (response) {
            console.log(JSON.stringify(response.data));
        })
        .catch(function (error) {
            console.log(error);
        });
    
    return {
        statusCode: 200,
        body: JSON.stringify(data),
    };
    

    FURTHER NOTE: Also, found out that using Netlify Secrets is a better way to hide guthub's token to increase security.

    const API_SECRET = process.env.API_SECRET;
    

    Then create an .env file with API_SECRET = ***** on root, add .env to .gitignore and finally on Netlify's platform creating the environment variables at ENVIRONMENT in the website's Build & Deploy tab.