This package defines a convention for storing field edition rules in your collection schema.
Aditionally, it can also automatically create default methods based on these rules.
meteor add utilities:smart-methods
The package provides two new properties.
insertableIf (user)
: called on theuser
performing the operation, should returntrue
orfalse
.editableIf (user, document)
: called on theuser
performing the operation, and thedocument
being operated on, and should returntrue
orfalse
.
Tasks = new Mongo.Collection("tasks");
const isLoggedIn = function (user) {
return !!user;
}
const isOwner = function (user, document) {
return user._id === document.owner;
}
const tasksSchema = new SimpleSchema({
text: {
type: String,
public: true,
insertableIf: isLoggedIn,
editableIf: isOwner
},
createdAt: {
type: Date,
public: true
},
owner: {
type: String,
public: true
},
checked: {
type: Boolean,
public: true,
insertableIf: isLoggedIn,
editableIf: function (user, document) {
if (document.private) {
return user._id === document.owner;
} else {
return true;
}
}
},
private: {
type: Boolean,
public: true,
insertableIf: isLoggedIn,
editableIf: isOwner
}
});
Tasks.attachSchema(tasksSchema);
This package can optionally creates three methods based on your schema.
Your methods will be:
-
create(document)
-
edit(documentId, modifier)
-
delete(documentId)
-
createName
,editName
,deleteName
[optional]: lets you specify names for each method. Note that the method will only be created if you provide a name for it (and in the case of thedelete
method, if you also provide adeleteCallback
option).
You can create these methods by calling Collection.smartMethods()
, with the following options:
createCallback (currentUser, document)
[optional]: called before a document is created. Should return a document.editCallback (currentUser, modifier, originalDocument)
[optional]: called before a document is edited. Should return a Mongo modifier.deleteCallback (currentUser, document)
[required]: called before a document is deleted. The document will not be deleted if this returnsfalse
. Note that thedelete
method will return whatever the callback returns.
Tasks.smartMethods({
createCallback: function (currentUser, document) {
document = _.extend(document, {
createdAt: new Date(),
owner: currentUser._id,
username: currentUser.username
});
return document;
},
editCallback: function (currentUser, modifier, originalDocument) {
modifier.$set.editedAt = new Date();
return modifier;
},
deleteCallback: function (currentUser, document) {
return currentUser._id === document.userId;
}
});
For a specific user, get an array of all the fields they have access to in a collection.
For a specific user and document, get an array of all the fields they can modify in this specific document.