react / wstein / node_modules / jest-cli / node_modules / node-haste / lib / ResourceMapSerializer.js
80657 views/**1* Copyright 2013 Facebook, Inc.2*3* Licensed under the Apache License, Version 2.0 (the "License");4* you may not use this file except in compliance with the License.5* You may obtain a copy of the License at6*7* http://www.apache.org/licenses/LICENSE-2.08*9* Unless required by applicable law or agreed to in writing, software10* distributed under the License is distributed on an "AS IS" BASIS,11* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12* See the License for the specific language governing permissions and13* limitations under the License.14*/15var fs = require('fs');1617var ResourceMap = require('./ResourceMap');1819/**20* A class that loads and stores ResourceMaps from and to a given file.21* Usese simple JSON functions to seralize/deserialize the data22*23* @class24* @param {Array.<ResourceLoader>} loaders25*/26function ResourceMapSerializer(loaders, options) {27options = options || {};28this.version = options.version || '0.1';29this.typeMap = {};30loaders.forEach(function(loader) {31loader.getResourceTypes().forEach(function(type) {32this.typeMap[type.prototype.type] = type;33}, this);34}, this);35}3637/**38* Loads and deserializes a map from a given path39* @param {String} path40* @param {ResourceMap} map41* @param {Function} callback42*/43ResourceMapSerializer.prototype.loadFromPath = function(path, callback) {44var me = this;45fs.readFile(path, 'utf-8', function(err, code) {46if (err || !code) {47callback(err, null);48return;49}5051var ser = JSON.parse(code);52var map = me.fromObject(ser);53callback(null, map);54});55};5657ResourceMapSerializer.prototype.loadFromPathSync = function(path) {58var code;59try {60code = fs.readFileSync(path, 'utf-8');61} catch (e) {62return null;63}64if (!code) {65return null;66}6768var ser = JSON.parse(code);69var map = this.fromObject(ser);70return map;71};7273ResourceMapSerializer.prototype.fromObject = function(ser) {74if (ser.version === this.version) {75var map = new ResourceMap();76ser.objects.forEach(function(obj) {77var type = this.typeMap[obj.type];78map.addResource(type.fromObject(obj));79}, this);80return map;81} else {82return null;83}84};8586/**87* Serializes and stores a map to a given path88* @param {String} path89* @param {ResourceMap} map90* @param {Function} callback91*/92ResourceMapSerializer.prototype.storeToPath = function(path, map, callback) {93var ser = this.toObject(map);94fs.writeFile(path, JSON.stringify(ser), 'utf-8', callback);95};9697ResourceMapSerializer.prototype.toObject = function(map) {98var ser = {99version: this.version,100objects: map.getAllResources().map(function(resource) {101return resource.toObject();102})103};104return ser;105};106107108module.exports = ResourceMapSerializer;109110111