-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.js
More file actions
70 lines (62 loc) · 1.88 KB
/
models.js
File metadata and controls
70 lines (62 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const uuid = require('uuid');
// This module provides volatile storage, using a `BlogPost`
// model. We haven't learned about databases yet, so for now
// we're using in-memory storage. This means each time the app stops, our storage
// gets erased.
// Don't worry too much about how BlogPost is implemented.
// Our concern in this example is with how the API layer
// is implemented, and getting it to use an existing model.
function StorageException(message) {
this.message = message;
this.name = "StorageException";
}
const BlogPosts = {
create: function(title, content, author, publishDate) {
const post = {
id: uuid.v4(),
title: title,
content: content,
author: author,
publishDate: publishDate || Date.now()
};
this.posts.push(post);
return post;
},
get: function(id=null) {
// if id passed in, retrieve single post,
// otherwise send all posts.
if (id !== null) {
return this.posts.find(post => post.id === id);
}
// return posts sorted (descending) by
// publish date
return this.posts.sort(function(a, b) {
return b.publishDate - a.publishDate
});
},
delete: function(id) {
const postIndex = this.posts.findIndex(
post => post.id === id);
if (postIndex > -1) {
this.posts.splice(postIndex, 1);
}
},
update: function(updatedPost) {
const {id} = updatedPost;
const postIndex = this.posts.findIndex(
post => post.id === updatedPost.id);
if (postIndex === -1) {
throw new StorageException(
`Can't update item \`${id}\` because doesn't exist.`)
}
this.posts[postIndex] = Object.assign(
this.posts[postIndex], updatedPost);
return this.posts[postIndex];
}
};
function createBlogPostsModel() {
const storage = Object.create(BlogPosts);
storage.posts = [];
return storage;
}
module.exports = {BlogPosts: createBlogPostsModel()};