editor-js/link

Is there any reason not to include data fetching logic?

planetbk9 opened this issue · 3 comments

I think that extracting meta data from url could be implemented in this extension.
But according to the guide, users should implement that logic in their own server.
I am just curious that there is some reason like security or something.

I had the same thought, but it turns out CORs will prevent one site from requesting the HTML from another. It's pretty easy to create an endpoint for this anyway. Here's my implementation with NestJS.

link.controller.ts

import { Controller, Get, Query } from '@nestjs/common'
import { LinkService } from 'src/link/link.service'

@Controller('link')
export class LinkController {
  constructor(private readonly linkService: LinkService) {}

  @Get()
  link(@Query('url') url: string) {
    return this.linkService.getMetadata(url)
  }
}

link.service.ts

import { Injectable, HttpService } from '@nestjs/common'
import { getMetadata } from 'page-metadata-parser'
import domino from 'domino'

@Injectable()
export class LinkService {
  constructor(private readonly httpService: HttpService) {}

  async getMetadata(url: string) {
    const res = await this.httpService.get(url).toPromise()
    const doc = domino.createWindow(res.data).document
    const meta = getMetadata(doc, url)
    return {
      success: 1,
      meta: {
        ...meta,
        image: {
          url: meta.image ?? meta.icon ?? '',
        },
      },
    }
  }
}

I am using editorjs with PHP and I have no idea of how I should do this at the moment.

Having some examples would be of real help, indeed.

My nodejs api query:



// cheerio is used for faster implementation
// https://www.npmjs.com/package/cheerio
// editorjs link previewer
app.get("/fetchUrl", async (req, res) => {
  let url = req.query.url;
  let resHTML = await fetch(new URL(url))
                      .catch((e) => console.log(e));
  const html = await resHTML.text();
  const $ = cheerio.load(html);

  // custom meta-tag function
  const getMetaTag = (value) => {
    return $(`meta[name=${value}]`).attr("content") ||
           $(`meta[property="og:${value}"]`).attr("content") ||
           $(`meta[property="twitter:${value}"]`).attr("content")
  }

  const resi = {
    success: 1,
    meta: {
      title: $("title").first().text(),
      description: getMetaTag("description"),
      image: {
        url: getMetaTag("image")
      }
    },
  };
  res.send(resi);
  return;
});