1const Joi = require('joi');
2const db = require('./connection');
3
4const schema = Joi.object().keys({
5 username: Joi.string().alphanum().required(),
6 subject: Joi.string().required(),
7 message: Joi.string().max(500).required(),
8 imageURL: Joi.string().uri({
9 scheme: [
10 /https?/
11 ]
12 })
13});
14
15const messages = db.get('messages');
16
17function getAll() {
18 return messages.find();
19}
20
21function create(message) {
22 if (!message.username) message.username = 'Anonymous';
23
24 const result = Joi.validate(message, schema);
25 if (result.error == null) {
26 message.created = new Date();
27 return messages.insert(message);
28 } else {
29 return Promise.reject(result.error);
30 }
31}
32
33module.exports = {
34 create,
35 getAll
36};
37