Posting via Discourse API and Firebase (Cloud Functions)

Hi everyone!

I’m running into some weird issues that I don’t know how to make sense of. I’m using the Discourse API to allow someone to post without signing-in. For security reasons, this is code that I’ll be running in a server environment, and the environment I’m going with the is the Node.js based Cloud Functions for Firebase.

My full code looks as follows:

const functions = require("firebase-functions");
const fetch = require('node-fetch');
const cors = require("cors")({ origin: true });

exports.makeDiscoursePost = functions.https.onRequest((request, response) => {
  cors(request, response, () => {
    let myHeaders = new Headers();
    myHeaders.append("Api-Key", "<removed>");
    myHeaders.append("Api-Username", "system");
    myHeaders.append("Content-Type", 'application/json');

    let requestOptions = {
      method: 'POST',
      headers: myHeaders,
      redirect: 'follow'
    };

    fetch("https://forum.kirupa.com/posts.json?title=Testingggg Discourse API, Part 2&raw=Making a brand new post using the API and seeing if things still work.", requestOptions)
      .then(r => r.json())
      .then(result => response.send(result))
      .catch(error => response.send(error));
  });
});

I’m confident this code works, for when I run the fetch code in isolation a post gets made. It is when it gets run via the functions environment, I get an “Internal Server Error”. When I read the logs, I see “Finished with status: crash”

Does anybody have any thoughts on what may be wrong here? Has anybody managed to get post creation working via Firebase’s functions?

(cc @blake - I followed your Node.js approach via using the HTTP request method, and I got the same results!)

Thanks,
Kirupa

I managed to fix this, and I am sharing my revised code in case someone else runs into this issue:

exports.sendfeedback = onRequest({ cors: "https://www.kirupa.com" }, (req, res) => {
  let myHeaders = new fetch.Headers();
  myHeaders.append("Api-Key", "removed");
  myHeaders.append("Api-Username", "kirupaBot");
  myHeaders.append("Content-Type", 'application/json');

  let requestOptions = {
    method: 'POST',
    headers: myHeaders,
    body: JSON.stringify({
      "raw": req.query.raw,
      "title": req.query.title
    })
  };

  fetch("https://forum.kirupa.com/posts.json", requestOptions)
    .then(r => r.json())
    .then(result => res.send(result))
    .catch(error => res.send(error));
});
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.