Skip to content

Instantly share code, notes, and snippets.

@xpepermint

xpepermint/index.js

Created Sep 30, 2017
Embed
What would you like to do?
Using RawModel in ExpressJS actions.
const { Model } = require("rawmodel");
const express = require("express");
/** Application context *******************************************************/
class Context {
constructor() {
this.db; // imaginary database
}
connect() {
this.db = []; // connect to database
}
close() {
this.db = []; // close database
}
}
/** Data layer ****************************************************************/
class User extends Model {
constructor(data = {}) {
super(data);
this.defineField("name", {
validate: [ { validator: "presence", message: "is required" } ],
});
this.populate(data);
}
async create(ctx) { // stores model data to the imaginary database
ctx.db.push(this.serialize());
}
static async all(ctx) { // returns all documents from the imaginary database
return ctx.db;
}
}
/** ExpressJS application *****************************************************/
const ctx = new Context(); // application context instance
const app = express(); // http application instance
app.get("/users", async (req, res, next) => { // route for reading users
res.json({ "users": await User.all(ctx) });
});
app.post("/users", async (req, res, next) => { // route for creating users
let user = new User(req.query);
try {
await user.validate();
await user.create(ctx);
} catch (e) {
await user.handle(e);
}
if (user.isValid()) {
res.json({ "user": user.serialize() });
} else {
res.json({ "errors": user.collectErrors() });
}
});
/** Application start *********************************************************/
(async () => {
await ctx.connect(); // connect to database
app.listen(4444); // start listening
})().catch(() => {
console.log(err);
app.close(); // close HTTP connection
ctx.close(); // close database connection
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.