From faf79d737f268b091533075d13932afe10ac80a2 Mon Sep 17 00:00:00 2001 From: Gael Date: Fri, 7 Dec 2018 09:06:59 -0800 Subject: [PATCH] Add some examples from presentation slides --- examples/activeRecord.js | 33 +++++++++++++++++++++++++++++ examples/framework.txt | 20 +++++++++++++++++ examples/inversionOfControl/bad.js | 16 ++++++++++++++ examples/inversionOfControl/good.js | 18 ++++++++++++++++ 4 files changed, 87 insertions(+) create mode 100644 examples/activeRecord.js create mode 100644 examples/framework.txt create mode 100644 examples/inversionOfControl/bad.js create mode 100644 examples/inversionOfControl/good.js diff --git a/examples/activeRecord.js b/examples/activeRecord.js new file mode 100644 index 0000000..f9a356c --- /dev/null +++ b/examples/activeRecord.js @@ -0,0 +1,33 @@ +const mongoose = require('mongoose'); + +const Schema = mongoose.Schema; + +const UserSchema = new Schema({ + name: { type: String, default: '' }, + email: { type: String, default: '' }, + role: { type: String, enum: ['USER', 'ADMIN'] }, +}); + +UserSchema.pre('save', function(next) { + if (!this.isNew) return next(); + + if (this.role != 'ADMIN' && this.email.endsWith('@admins.com')) { + next(new Error('Only admins can use @admins.com emails')); + } else { + next(); + } +}); + +UserSchema.methods = { + isAdmin: function() { + return this.role === 'ADMIN'; + }, +}; + +UserSchema.statics = { + findByEmail: function(email) { + return this.findOne({ email }); + }, +}; + +mongoose.model('User', UserSchema); diff --git a/examples/framework.txt b/examples/framework.txt new file mode 100644 index 0000000..99e903e --- /dev/null +++ b/examples/framework.txt @@ -0,0 +1,20 @@ +/src + /controllers + /user.js + /company.js + /product.js + /cart.js + /views + /user.js + /company.js + /product.js + /cart.js + /models + /user.js + /company.js + /product.js + /cart.js + + + + \ No newline at end of file diff --git a/examples/inversionOfControl/bad.js b/examples/inversionOfControl/bad.js new file mode 100644 index 0000000..e5e26f5 --- /dev/null +++ b/examples/inversionOfControl/bad.js @@ -0,0 +1,16 @@ +const dbClient = require('dbClient'); +const notificationService = require('notificationService'); + +async function someUseCase() { + const account = await dbClient.collection('accounts').findOne({ + _id: 'someId', + }); + + if (account.type === 'USER') { + notificationService.sendNotification(account); + } +} + +module.exports = { + someUseCase, +}; diff --git a/examples/inversionOfControl/good.js b/examples/inversionOfControl/good.js new file mode 100644 index 0000000..e71898b --- /dev/null +++ b/examples/inversionOfControl/good.js @@ -0,0 +1,18 @@ +module.exports = ({ + accountCollection: { findAccount }, + notificationService: { sendNotification }, +}) => { + async function someUseCase() { + const account = await findAccount({ + _id: 'someId', + }); + + if (account.type === 'USER') { + sendNotification(account); + } + } + + return { + someUseCase, + }; +};