Skip to content
This repository has been archived by the owner on Oct 1, 2019. It is now read-only.

Commit

Permalink
Implement rendering of text into html for story posts
Browse files Browse the repository at this point in the history
  • Loading branch information
voidxnull committed Jun 16, 2017
1 parent 223cbcd commit 7d3c0dc
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
12 changes: 12 additions & 0 deletions migrations/20170615170503_posts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export async function up(knex) {
await knex.schema.table('posts', table => {
table.text('html');
table.string('text_type');
});
}

export async function down(knex) {
await knex.schema.table('posts', table => {
table.dropColumns(['html', 'text_type']);
});
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@
"redux": "~3.6.0",
"redux-immutablejs": "0.0.8",
"reselect": "~3.0.0",
"sanitize-html": "^1.14.1",
"sendgrid": "^2.0.0",
"slug": "^0.9.1",
"smoothscroll-polyfill": "^0.3.4",
Expand Down
36 changes: 36 additions & 0 deletions src/api/db/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import { break as breakGraphemes, countBreaks } from 'grapheme-breaker';
import { OnigRegExp } from 'oniguruma';
import Checkit from 'checkit';
import MarkdownIt from 'markdown-it';
import sanitizeHtml from 'sanitize-html';
import slug from 'slug';

import { uploadAttachment, downloadAttachment, generateName } from '../../utils/attachments';
Expand Down Expand Up @@ -182,6 +183,41 @@ export function initBookshelfFromKnex(knex) {

const Post = bookshelf.Model.extend({
tableName: 'posts',
initialize() {
this.on('saving', this.ensureTextType.bind(this));
this.on('saving', this.renderHtml.bind(this));
},
ensureTextType() {
const allowedTypes = ['markdown', 'html', 'plain'];

// The default type of text is 'plain'. Plain text must be rendered using posts.text attribute.
if (!_.includes(allowedTypes, this.get('text_type'))) {
this.set('text_type', 'plain');
this.set('html', null);
}
},
renderHtml() {
const text = this.get('text');
if (!_.isString(text) || _.isEmpty(text)) {
return;
}

let html;
switch (this.get('text_type')) {
case 'markdown': {
html = postMarkdown.render(text);
break;
}
case 'html': {
// Adjust the defaults if needed.
html = sanitizeHtml(text);
break;
}
default: return;
}

this.set('html', html);
},
/**
* Common logic for creating and updating. Must only be used for posts with text.
*/
Expand Down

0 comments on commit 7d3c0dc

Please sign in to comment.