Skip to content

Instantly share code, notes, and snippets.

@nickstewart95

nickstewart95/index.js Secret

Created Dec 15, 2020
Embed
What would you like to do?
const express = require("express");
const jsdom = require('jsdom')
const blockTools = require('@sanity/block-tools');
const Schema = require('@sanity/schema');
const defaultSchema = require('./defaultSchema');
const { JSDOM } = jsdom;
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.listen(3000, () => {
console.log("Server running on port 3000");
});
app.post('/convert', (req, res) => {
var text = Buffer.from(req.param('html'), 'base64'); // Ta-da
var notFormatted = '<html>' + text + '</html>';
var blockContentType = defaultSchema.get('blogPost').fields.find(field => field.name === 'body').type;
const blocks = blockTools.htmlToBlocks(
notFormatted,
blockContentType,
{
parseHtml: html => new JSDOM(html).window.document,
rules: [
{
deserialize (el, next, block) {
if (el.tagName === 'IMG') {
return block({
_type: 'image',
_sanityAsset: `image@${el
.getAttribute('src')
.replace(/^\/\//, 'https://')}`
});
}
if (
el.tagName.toLowerCase() === 'p' &&
el.childNodes.length === 1 &&
el.childNodes.tagName &&
el.childNodes[0].tagName.toLowerCase() === 'img'
) {
return block({
_type: 'image',
_sanityAsset: `image@${el.childNodes[0]
.getAttribute('src')
.replace(/^\/\//, 'https://')}`
});
}
return undefined;
}
},
{
deserialize (el, next, block) {
if (el.tagName === 'ROW') {
var children = Array.prototype.slice.call(el.childNodes);
var childrenHolder = [];
for (child in children) {
if (children[child].tagName === 'GALLERYIMAGE' || children[child].tagName === 'IMG') {
var tmp = {
_type: 'image',
_sanityAsset: `image@${children[child]
.getAttribute('src')
.replace(/^\/\//, 'https://')}`
};
} else {
var tmp = {
_type: 'textContent',
'text': children[child].textContent
};
}
childrenHolder.push(tmp);
}
return block({
_type: 'cluster',
items: childrenHolder,
});
}
}
},
{
deserialize (el, next, block) {
if (el.tagName === 'CTABUTTON') {
return block({
_type: 'ctaButton',
title: el.textContent,
link: el.getAttribute('href')
});
}
}
},
]
}
);
return res.send(blocks);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment