Created
July 27, 2014 08:08
Photo Model & Service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var mongoose = require('mongoose'), | |
Schema = mongoose.Schema; | |
var PhotoSchema = new Schema({ | |
type: { | |
type: String, | |
enum: ['png', 'jpeg', 'gif'] | |
}, | |
width: Number, | |
height: Number, | |
size: Number, | |
image: String, | |
ref: { | |
collection: String, | |
id: Schema.Types.ObjectId | |
}, | |
created_at: { | |
type: Date, | |
default: Date.now, | |
index: true | |
} | |
}); | |
module.exports = mongoose.model('Photo', PhotoSchema); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var Bluebird = require('bluebird'), | |
_ = require('lodash'), | |
Photo = localrequire.model('photo'); | |
exports.create = function(contents) { | |
_.forOwn(contents, function(value, key) { | |
if (!_.contains(['type', 'width', 'height', 'size', 'image', 'ref'], key)) delete contents[key]; | |
}); | |
var deferred = Bluebird.defer(); | |
new Photo(contents).save(function(err, photo) { | |
if (err) return deferred.reject(err); | |
deferred.resolve(photo); | |
}); | |
return deferred.promise; | |
}; | |
exports.read = function(id) { | |
var deferred = Bluebird.defer(); | |
Photo.findById(id).exec(function(err, photo) { | |
if (err) { | |
if (err.name === 'CastError' && err.type === 'ObjectId') | |
return deferred.reject(Errors.PhotoNotFound(id)); | |
else | |
return deferred.reject(err); | |
} | |
if (!photo) return deferred.reject(Errors.PhotoNotFound(id)); | |
deferred.resolve(photo); | |
}); | |
return deferred.promise; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment