| 1 | export default function buildMakeComment ({ Id, md5, sanitize, makeSource }) { |
| 2 | return function makeComment ({ |
| 3 | author, |
| 4 | createdOn = Date.now(), |
| 5 | id = Id.makeId(), |
| 6 | source, |
| 7 | modifiedOn = Date.now(), |
| 8 | postId, |
| 9 | published = false, |
| 10 | replyToId, |
| 11 | text |
| 12 | } = {}) { |
| 13 | if (!Id.isValidId(id)) { |
| 14 | throw new Error('Comment must have a valid id.') |
| 15 | } |
| 16 | if (!author) { |
| 17 | throw new Error('Comment must have an author.') |
| 18 | } |
| 19 | if (author.length < 2) { |
| 20 | throw new Error("Comment author's name must be longer than 2 characters.") |
| 21 | } |
| 22 | if (!postId) { |
| 23 | throw new Error('Comment must contain a postId.') |
| 24 | } |
| 25 | if (!text || text.length < 1) { |
| 26 | throw new Error('Comment must include at least one character of text.') |
| 27 | } |
| 28 | if (!source) { |
| 29 | throw new Error('Comment must have a source.') |
| 30 | } |
| 31 | if (replyToId && !Id.isValidId(replyToId)) { |
| 32 | throw new Error('If supplied. Comment must contain a valid replyToId.') |
| 33 | } |
| 34 | |
| 35 | let sanitizedText = sanitize(text).trim() |
| 36 | if (sanitizedText.length < 1) { |
| 37 | throw new Error('Comment contains no usable text.') |
| 38 | } |
| 39 | |
| 40 | const validSource = makeSource(source) |
| 41 | const deletedText = '.xX This comment has been deleted Xx.' |
| 42 | let hash |
| 43 | |
| 44 | return Object.freeze({ |
| 45 | getAuthor: () => author, |
| 46 | getCreatedOn: () => createdOn, |
| 47 | getHash: () => hash || (hash = makeHash()), |
| 48 | getId: () => id, |
| 49 | getModifiedOn: () => modifiedOn, |
| 50 | getPostId: () => postId, |
| 51 | getReplyToId: () => replyToId, |
| 52 | getSource: () => validSource, |
| 53 | getText: () => sanitizedText, |
| 54 | isDeleted: () => sanitizedText === deletedText, |
| 55 | isPublished: () => published, |
| 56 | markDeleted: () => { |
| 57 | sanitizedText = deletedText |
| 58 | author = 'deleted' |
| 59 | }, |
| 60 | publish: () => { |