diff --git a/src/core/Image.js b/src/core/Image.js index 2f1db37d..332dcfbd 100644 --- a/src/core/Image.js +++ b/src/core/Image.js @@ -1,11 +1,45 @@ const Data = require('./Data') const {findOne} = require('../lib/store') +const {mapOf} = require('../lib/common') const store = () => Data.getStore(Image) class Image { static async findById(id) { - return findOne(store(), {_id: id}) + const data = await findOne(store(), {_id: id}) + if (!data) return null + + const artifacts = data.data + return new Image({...data, artifacts}) + } + + constructor({hash, file, artifacts}) { + this.hash = hash + this.file = file + + this.artifacts = mapOf(ImageArtifact, artifacts) + } + + getArtifact(size) { + return this.artifacts.get(size) + } + + findArtifact(sizes) { + for (let size of sizes) { + const a = this.getArtifact(size) + if (a) return a + } + + return null + } +} + +class ImageArtifact { + constructor({url, size, width, height}) { + this.url = url + this.size = size + this.width = width + this.height = height } } diff --git a/src/core/ImageArtifactType.js b/src/core/ImageArtifactType.js new file mode 100644 index 00000000..f731f278 --- /dev/null +++ b/src/core/ImageArtifactType.js @@ -0,0 +1,11 @@ +class ImageArtifact { + constructor() { + throw new Error('Cannot create instance of ImageArtifact') + } +} + +ImageArtifact.MEDIUM = 'medium' +ImageArtifact.BIG = 'big' +ImageArtifact.ORIGIN = 'origin' + +module.exports = ImageArtifact diff --git a/src/lib/common.js b/src/lib/common.js index 0fd2b0db..cd0f9d2e 100644 --- a/src/lib/common.js +++ b/src/lib/common.js @@ -31,6 +31,22 @@ function any(list) { return list.reduce((t, i) => t || i, false) } +/** + * + * {a: {}, b: {}, ...} -> Map (a: Class, b: Class) + * + * @param Class + * @param object + */ +function mapOf(Class, object) { + return Object + .entries(object) + .reduce((map, i) => ( + map.set(i[0], new Class(i[1])) + ), new Map()) +} + exports.compose = compose exports.all = all exports.any = any +exports.mapOf = mapOf