Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: ability to add simple pre and post hooks #12

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,26 @@ const fixReferences = (decorator, schema) => {
});
};

const addPreMiddleware = (schema, model) => {
const keys = Object.keys(model.pre);

keys.forEach((k) => {
if(typeof model.pre[k] === 'function') {
schema.pre(k, model.pre[k]);
}
});
};

const addPostMiddleware = (schema, model) => {
const keys = Object.keys(model.post);

keys.forEach((k) => {
if (typeof model.post[k] === "function") {
schema.post(k, model.post[k]);
}
});
};

let decorator;

async function mongooseConnector(
Expand All @@ -72,6 +92,14 @@ async function mongooseConnector(

if (model.virtualize) model.virtualize(schema);

if(model.pre) {
addPreMiddleware(schema, model);
}

if(model.post) {
addPostMiddleware(schema, model);
}

if (useNameAndAlias) {
/* istanbul ignore next */
if (model.alias === undefined)
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

335 changes: 193 additions & 142 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,148 +5,199 @@ const tap = require("tap");
const fastifyMongoose = require("./index");

class PostClass {
get fullTitle() {
return `Title: ${this.title}`;
}
get fullTitle() {
return `Title: ${this.title}`;
}
}

tap.test("fastify.mongoose should exist", async test => {
test.plan(12);

fastify.register(fastifyMongoose.plugin, {
uri: "mongodb://localhost:27017/test",
settings: {
useNewUrlParser: true,
config: {
autoIndex: true
}
},
models: [
{
name: "posts",
alias: "Post",
schema: {
title: {
type: String,
required: true
},
content: {
type: String,
required: true
},
author: {
type: "ObjectId",
ref: "Account",
validateExistance: true
}
},
class: PostClass
},
{
name: "accounts",
alias: "Account",
schema: {
username: {
type: String
},
password: {
type: String,
select: false,
required: true
},
email: {
type: String,
unique: true,
required: true,
validate: {
validator: v => {
// Super simple email regex: https://stackoverflow.com/a/4964763/7028187
return /^.+@.{2,}\..{2,}$/.test(v);
},
message: props => `${props.value} is not a valid email!`
}
},
posts: [
{
type: "ObjectId",
ref: "Post",
validateExistance: true
}
],
createdAtUTC: {
type: Date,
required: true
}
}
}
],
useNameAndAlias: true
});

fastify.post("/", async ({ body }, reply) => {
const { username, password, email } = body;
const createdAtUTC = new Date();
const account = new fastify.mongoose.Account({
username,
password,
email,
createdAtUTC
});
await account.save();
return await fastify.mongoose.Account.findOne({ email });
});

fastify.patch("/", async ({ body }, reply) => {
const { title, content, author } = body;
const post = new fastify.mongoose.Post({
title,
content,
author
});
await post.save();
const foundPost = await fastify.mongoose.Post.findById(post._id);
return foundPost.toObject({ virtuals: true });
});

try {
await fastify.ready();
test.ok(fastify.mongoose.instance);
test.ok(fastify.mongoose.Account);

const testEmail = `${(+new Date()).toString(36).slice(-5)}@example.com`;

let { statusCode, payload } = await fastify.inject({
method: "POST",
url: "/",
payload: {
username: "test",
password: "pass",
email: testEmail
}
});

const { username, password, email, _id } = JSON.parse(payload);
test.strictEqual(statusCode, 200);
test.strictEqual(username, "test");
test.strictEqual(password, undefined);
test.strictEqual(email, testEmail);

({ statusCode, payload } = await fastify.inject({
method: "PATCH",
url: "/",
payload: { author: _id, title: "Hello World", content: "foo bar" }
}));

const { title, fullTitle, content, author } = JSON.parse(payload);
test.strictEqual(fullTitle, "Title: Hello World");
test.strictEqual(title, "Hello World");
test.strictEqual(content, "foo bar");
test.strictEqual(author, _id);

test.ok(fastifyMongoose.decorator().instance);
test.ok(fastifyMongoose.decorator().Account);
} catch (e) {
test.fail("Fastify threw", e);
}
fastify.close();
tap.test("fastify.mongoose should exist", async (test) => {
let hasHitPostSaveHook = false;
test.plan(15);

fastify.register(fastifyMongoose.plugin, {
uri: "mongodb://localhost:27017/test",
settings: {
useNewUrlParser: true,
config: {
autoIndex: true,
},
},
models: [
{
name: "posts",
alias: "Post",
schema: {
title: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
author: {
type: "ObjectId",
ref: "Account",
validateExistance: true,
},
},
class: PostClass,
},
{
name: "accounts",
alias: "Account",
schema: {
username: {
type: String,
},
password: {
type: String,
select: false,
required: true,
},
email: {
type: String,
unique: true,
required: true,
validate: {
validator: (v) => {
// Super simple email regex: https://stackoverflow.com/a/4964763/7028187
return /^.+@.{2,}\..{2,}$/.test(v);
},
message: (props) => `${props.value} is not a valid email!`,
},
},
posts: [
{
type: "ObjectId",
ref: "Post",
validateExistance: true,
},
],
createdAtUTC: {
type: Date,
required: true,
},
},
},
{
name: "preandpost",
alias: "PreAndPost",
schema: {
someField: {
type: String,
required: true,
},
someOtherField: {
type: String,
required: true,
},
newField: {
type: String,
},
},
pre: {
save: function (next) {
this.someField = "not a dummy!";
next();
},
},
post: {
save: function (doc) {
hasHitPostSaveHook = true;
},
},
},
],
useNameAndAlias: true,
});

fastify.post("/", async ({ body }, reply) => {
const { username, password, email } = body;
const createdAtUTC = new Date();
const account = new fastify.mongoose.Account({
username,
password,
email,
createdAtUTC,
});
await account.save();
return await fastify.mongoose.Account.findOne({ email });
});

fastify.patch("/", async ({ body }, reply) => {
const { title, content, author } = body;
const post = new fastify.mongoose.Post({
title,
content,
author,
});
await post.save();
const foundPost = await fastify.mongoose.Post.findById(post._id);
return foundPost.toObject({ virtuals: true });
});

fastify.get("/", async (request, reply) => {
const preandpost = new fastify.mongoose.PreAndPost({
someField: "dummy",
someOtherField: "smartie",
});
await preandpost.save();
const foundPost = await fastify.mongoose.PreAndPost.findById(
preandpost._id
);
return foundPost.toObject({ virtuals: true });
});

try {
await fastify.ready();
test.ok(fastify.mongoose.instance);
test.ok(fastify.mongoose.Account);

const testEmail = `${(+new Date()).toString(36).slice(-5)}@example.com`;

let { statusCode, payload } = await fastify.inject({
method: "POST",
url: "/",
payload: {
username: "test",
password: "pass",
email: testEmail,
},
});

const { username, password, email, _id } = JSON.parse(payload);
test.strictEqual(statusCode, 200);
test.strictEqual(username, "test");
test.strictEqual(password, undefined);
test.strictEqual(email, testEmail);

({ statusCode, payload } = await fastify.inject({
method: "PATCH",
url: "/",
payload: { author: _id, title: "Hello World", content: "foo bar" },
}));

const { title, fullTitle, content, author } = JSON.parse(payload);
test.strictEqual(fullTitle, "Title: Hello World");
test.strictEqual(title, "Hello World");
test.strictEqual(content, "foo bar");
test.strictEqual(author, _id);

({ payload } = await fastify.inject({
method: "GET",
url: "/",
}));

const { someField, someOtherField, newField } = JSON.parse(payload);
test.strictEqual(someField, "not a dummy!");
test.strictEqual(someOtherField, "smartie");
test.strictEqual(hasHitPostSaveHook, true);

test.ok(fastifyMongoose.decorator().instance);
test.ok(fastifyMongoose.decorator().Account);
} catch (e) {
test.fail("Fastify threw", e);
}
fastify.close();
});