API Retrieve Post relative URLs

Hi all

I’m using the discourse API to retrieve a Topic / all its posts and then each post and and its content

My forums are hosted on forums.xxx.com
I use the API to retrieve the posts and place them on my www.xxx.com domain and link back and forth between the two,

This all works except that the content i pull through uses relative URLs - so a link to a user (when on the forums domain) would be forums.xxx.com/u/the-user

As i pull that post through to my www.x domain, it links to www.xxx.com/u/the-user - which obviously does not exist.
The same problem extends to any emojis or images included in the post - the links are broken.

Is there anyway to have the links coming through (i use content: data['cooked']) to link back to the original domain?

i actually asked chat GPT the same question and got a working answer straight away

using a helper method to replace the urls inside the cooked data

def update_urls(content)
    forum_domain = 'https://forums.xxx.com'

    # Update href attributes
    content.gsub!(/href="(\/[^"]*)"/i) { |match| "href=\"#{forum_domain}#{$1}\"" }

    # Update src attributes
    content.gsub!(/src="(\/[^"]*)"/i) { |match| "src=\"#{forum_domain}#{$1}\"" }

    content
  end

So i’ll leave this here for anyone else - if anyone has a more elegant out of the box solution i would be interested

2 Likes

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