Skip to content

Instantly share code, notes, and snippets.

@xpepermint
Created September 30, 2017 16:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xpepermint/887a76bb3b1730709a760053a5ffff97 to your computer and use it in GitHub Desktop.
Save xpepermint/887a76bb3b1730709a760053a5ffff97 to your computer and use it in GitHub Desktop.
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