Add events model

This commit is contained in:
Chris Blanchard 2015-12-29 16:25:23 +00:00
parent e2ecc18256
commit 5776c5fc3a
2 changed files with 98 additions and 0 deletions

42
db/models/event.js Normal file
View file

@ -0,0 +1,42 @@
"use strict";
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const path = require("path");
const pubsub = require(path.join(__dirname, "../../lib/event/pubsub.js"));
const winston = require("winston");
const eventSchema = new Schema({
type: { type: String, required: true },
description: { type: String },
meta: { type: Schema.Types.Mixed },
public: { type: Boolean, default: false },
createdAt: { type: Date, default: Date.now, required: true }
});
eventSchema.index({ createdAt: -1 });
eventSchema.index({ type: 1 });
eventSchema.post("save", event => {
pubsub.emit("newEvent", event);
});
eventSchema.statics.joiner = function (user) {
winston.info("Gather Joiner", JSON.stringify(user));
this.create({
type: "gather:joiner",
description: `${user.username} joined the gather`,
public: true
});
};
eventSchema.statics.leaver = function (user) {
winston.info("Gather Leaver", JSON.stringify(user));
this.create({
type: "gather:leaver",
description: `${user.username} left the gather`,
public: true
});
};
module.exports = mongoose.model('Event', eventSchema);

56
spec/event.js Normal file
View file

@ -0,0 +1,56 @@
"use strict";
const helper = require("./helpers/index.js");
const Event = helper.Event;
const assert = require("chai").assert;
const async = require("async");
const pubsub = helper.eventPubSub;
describe("Event Model", () => {
before(done => {
helper.clearDb(done);
});
afterEach(done => {
helper.clearDb(done);
});
describe(".create", () => {
it ("creates a new event", done => {
const event = {
type: "event",
description: "An event occurred",
meta: {
foo: "bar"
}
};
Event.create(event, (error, result) => {
if (error) return done(error);
assert.equal(result.type, event.type);
assert.equal(result.description, event.description);
assert.equal(result.description, event.description);
assert.isDefined(result.createdAt);
done();
});
});
it ("emits an event when an event is created", done => {
const event = {
type: "event",
description: "An event occurred",
meta: {
foo: "bar"
}
};
Event.create(event, error => {
if (error) return done(error);
});
pubsub.once("newEvent", newEvent => {
assert.equal(newEvent.type, event.type);
assert.equal(newEvent.description, event.description);
assert.equal(newEvent.description, event.description);
assert.isDefined(newEvent.createdAt);
done();
});
});
});
});