This repository has been archived on 2022-08-14. You can view files and clone it, but cannot push or open issues or pull requests.
outline/server/models/Document.js

85 lines
2.0 KiB
JavaScript
Raw Normal View History

2016-05-26 05:38:45 +00:00
import slug from 'slug';
import randomstring from 'randomstring';
2016-04-29 05:25:37 +00:00
import {
DataTypes,
sequelize,
} from '../sequelize';
2016-05-23 05:08:09 +00:00
import {
convertToMarkdown,
2016-07-24 22:32:31 +00:00
} from '../../frontend/utils/markdown';
2016-06-04 19:30:05 +00:00
import {
truncateMarkdown,
} from '../utils/truncate';
2016-05-22 14:25:13 +00:00
import User from './User';
2016-06-26 18:23:03 +00:00
import Revision from './Revision';
2016-04-29 05:25:37 +00:00
slug.defaults.mode = 'rfc3986';
2016-05-26 05:38:45 +00:00
const generateSlug = (title, urlId) => {
const slugifiedTitle = slug(title);
return `${slugifiedTitle}-${urlId}`;
};
2016-08-12 13:36:48 +00:00
const createRevision = async (doc) => {
// Create revision of the current (latest)
await Revision.create({
title: doc.title,
text: doc.text,
html: doc.html,
preview: doc.preview,
userId: doc.lastModifiedById,
documentId: doc.id,
});
};
2016-06-26 18:23:03 +00:00
const documentBeforeSave = (doc) => {
doc.html = convertToMarkdown(doc.text);
doc.preview = truncateMarkdown(doc.text, 160);
doc.revisionCount = doc.revisionCount + 1;
return doc;
};
2016-04-29 05:25:37 +00:00
const Document = sequelize.define('document', {
id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true },
2016-05-26 05:38:45 +00:00
urlId: { type: DataTypes.STRING, primaryKey: true },
2016-05-26 05:47:31 +00:00
private: { type: DataTypes.BOOLEAN, defaultValue: true },
2016-05-20 03:46:34 +00:00
title: DataTypes.STRING,
text: DataTypes.TEXT,
2016-05-23 05:08:09 +00:00
html: DataTypes.TEXT,
preview: DataTypes.TEXT,
revisionCount: { type: DataTypes.INTEGER, defaultValue: 0 },
2016-06-22 07:01:57 +00:00
parentDocumentId: DataTypes.UUID,
2016-06-26 18:23:03 +00:00
lastModifiedById: {
type: 'UUID',
allowNull: false,
references: {
model: 'users',
},
2016-06-26 18:23:03 +00:00
},
2016-05-23 05:08:09 +00:00
}, {
paranoid: true,
2016-05-23 05:08:09 +00:00
hooks: {
2016-05-26 05:38:45 +00:00
beforeValidate: (doc) => {
doc.urlId = randomstring.generate(15);
},
2016-06-26 18:23:03 +00:00
beforeCreate: documentBeforeSave,
beforeUpdate: documentBeforeSave,
2016-08-12 13:36:48 +00:00
afterCreate: async (doc) => await createRevision(doc),
afterUpdate: async (doc) => await createRevision(doc),
2016-05-26 05:38:45 +00:00
},
instanceMethods: {
buildUrl() {
const slugifiedTitle = slug(this.title);
return `${slugifiedTitle}-${this.urlId}`;
2016-06-21 06:12:56 +00:00
},
getUrl() {
return `/documents/${this.id}`;
2016-06-21 06:12:56 +00:00
},
},
2016-04-29 05:25:37 +00:00
});
2016-05-22 14:25:13 +00:00
Document.belongsTo(User);
2016-04-29 05:25:37 +00:00
2016-05-20 03:46:34 +00:00
export default Document;