From d46bddbc371de708a21b976ffcc0e37550de1bfc Mon Sep 17 00:00:00 2001 From: himetani_cafe Date: Tue, 26 Jan 2016 04:59:44 +0900 Subject: [PATCH] [DEBUG] modify the way to import and export Eos, DB class if you import Eos or DB, var eos = require('path/to/Eos.js').instance var db = require('path/to/DB.js').instance db.init(); // return promise --- package.json | 2 +- server/api/v1/fileUpload/index.js | 46 +- server/app.js | 29 +- server/class/DB.js | 1027 +++++++++++++++++++------------------ server/class/Eos.js | 424 ++++++++------- test/mocha/DB.test.js | 91 +--- test/mocha/Eos.test.js | 4 +- 7 files changed, 784 insertions(+), 839 deletions(-) diff --git a/package.json b/package.json index 22abeb4..b94386b 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "description": "", "main": "./server/app.js", "scripts": { - "test": "mocha test/mocha/DB.test.js" + "test": "mocha test/mocha/*.test.js" }, "author": "", "license": "ISC", diff --git a/server/api/v1/fileUpload/index.js b/server/api/v1/fileUpload/index.js index 5a99827..84d3b88 100644 --- a/server/api/v1/fileUpload/index.js +++ b/server/api/v1/fileUpload/index.js @@ -4,31 +4,35 @@ var express = require('express'); var router = express.Router() var path = require('path') var formidable = require('formidable') -var DB = require(__dirname + '/../../../../server/class/DB'); +var DB = require(__dirname + '/../../../../server/class/DB').instance; router.post('/', function(req, res) { - DB() - .then(function(db) { - var form = new formidable.IncomingForm(); - if(process.env['NODE_ENV'] === 'debug') { - form.uploadDir = __dirname + '/../../../../user-specific-files/workspace.debug'; - } else { - form.uploadDir = __dirname + '/../../../../user-specific-files/workspace'; - } + var form = new formidable.IncomingForm(); + if(process.env['NODE_ENV'] === 'debug') { + form.uploadDir = __dirname + '/../../../../user-specific-files/workspace.debug'; + } else { + form.uploadDir = __dirname + '/../../../../user-specific-files/workspace'; + } - form.parse(req, function(err, fields, files) { - var parentDirectory = fields['parentDirectory']; - var keys = Object.keys(files); - keys.forEach(function(f) { - db.createFile(files[f].name, parentDirectory) - .then(function(path) { - files[f].path = form.uploadDir + '/' + path; - console.log(files[f].path); - }); - }); - res.send("done"); - }); + DB.createFile('hoge.txt','/') + .then(function(r) { + console.log(r); }); + + /* + form.parse(req, function(err, fields, files) { + var parentDirectory = fields['parentDirectory']; + var keys = Object.keys(files); + keys.forEach(function(f) { + db.createFile(files[f].name, parentDirectory) + .then(function(path) { + files[f].path = form.uploadDir + '/' + path; + console.log(files[f].path); + }); + }); + res.send("done"); + }); + */ }); module.exports = router; diff --git a/server/app.js b/server/app.js index c2c4222..bc9f28e 100644 --- a/server/app.js +++ b/server/app.js @@ -2,22 +2,29 @@ 'use strict'; -var express = require('express'), - config = require('./config'), - app = express(), - EventEmitter = require('events').EventEmitter, - emitter = new EventEmitter, - server = require('http').Server(app) +var express = require('express'); +var config = require('./config'); +var app = express(); +var EventEmitter = require('events').EventEmitter; +var emitter = new EventEmitter; +var server = require('http').Server(app) -require('./express')(app) -require('./routes')(app) +require('./express')(app); +require('./routes')(app); + +// DBのコンストラクタを実行 +var DB = require('./class/DB').instance; +DB.init() +.then(function(methods) { + console.log(DB); +}); var server = app.listen(config.port, config.ip, function () { console.log('Zephyr listening at http://%s:%s', config.ip, config.port); console.log(app.get('env')) }); -var io = require('socket.io').listen(server) -require('./ws')(io) +var io = require('socket.io').listen(server); +require('./ws')(io); -exports = module.exports = app; +//exports = module.exports = app; diff --git a/server/class/DB.js b/server/class/DB.js index d37b7a9..f145554 100644 --- a/server/class/DB.js +++ b/server/class/DB.js @@ -3,582 +3,585 @@ * * @returns {object} */ -function DB() { - 'use strict'; - - var fs = require('fs'); - var Sequelize = require('sequelize'); - var co = require('co'); - var uuid = require('node-uuid'); - - var sequelize; - var test = 'hello'; - - /** - * sync - * - * @returns {promise} - */ - function sync() { - return new Promise(function(resolve) { - var force = process.env.NODE_ENV !== 'production'; - Files.sync({force: force}) - .then(function() { - return existDirectory(q); - }) - .catch(function() { +'use strict'; + +var fs = require('fs'); +var Sequelize = require('sequelize'); +var co = require('co'); +var uuid = require('node-uuid'); + +var sequelize; +var test = 'hello'; +var Files; // Model object of sequelize + + var instance = { + init: init, + sayHello: function() { + return test; + }, + getDirectoryParentId: getDirectoryParentId, + getDirectoryId: getDirectoryId, + getDirectory: getDirectory, + existFile: existFile, + notExistFile: notExistFile, + existDirectory: existDirectory, + notExistDirectory: notExistDirectory, + createFile: createFile, + removeFile: removeFile, + createDirectory: createDirectory, + test1: test1, + test2: test2 + /* + removeDirectory: removeDirectory, + getFilename: getFilename, + moveFile: moveFile, + moveDirectory: moveDirectory + */ +}; + +/** + * init + * @constructor + * @returns {promise} + */ + +/** + * productionモード時は、db.workspaceを永続化させる + * DEBUGモードの時は、db.debugを実行毎に作成する。 + * DEBUGモードの時は、sync()の中で、/レコードがFilesテーブルに追加される。 + * モードの切り替えは環境変数NODE_ENVで行っている。 + * zephyr serveコマンドが実行されるとNODE_ENV = 'production' + * zephyr debugコマンドが実行されるとNODE_ENV = 'debug' + * となる。 + * それぞれの設定は$ZEOHYR_HOME/cli/zephyr-serve, $ZEPHYR_HOME/zephyre_debugを参照 + */ + + function init() { + var dbPath; + var dbOption = { + dialect: 'sqlite' + }; + + if(process.env['NODE_ENV'] === 'production') { + dbPath = __dirname + '/../../user-specific-files/db/db.workspace'; + // if doesn't exist workspace.db, create. + try { + fs.accessSync(dbPath, fs.R_OK | fs.W_OK); + } catch(e) { + fs.writeFileSync(dbPath, ''); + } + dbOption.storage = dbPath; + + } else if(process.env['NODE_ENV'] === 'debug') { + dbPath = __dirname + '/../../user-specific-files/db/db.debug'; + try { + fs.accessSync(dbPath, fs.R_OK | fs.W_OK); + fs.unlinkSync(dbPath); + } catch(e) { + } + + fs.writeFileSync(dbPath, ''); + dbOption.storage = dbPath; + } + + sequelize = new Sequelize('','','', dbOption); + + Files = sequelize.define('file', { + fileId: { + type: Sequelize.UUID, + field: 'file_id', + primaryKey: true + }, + name: { + type: Sequelize.STRING, + field: 'name', + allowNull: false + }, + parentId: { + type: Sequelize.UUID, + field: 'parent_id', + allowNull: false + }, + fileType: { + type: Sequelize.ENUM(0,1), + field: 'file_type', + allowNull: false + } + }); + + var force = process.env.NODE_ENV !== 'production'; + return Files.sync({force: force}) + .then(function() { + return insertRoot(); + }); + } + + +/** + * sync + * + * @returns {promise} + */ +function insertRoot() { + return new Promise(function(resolve, reject) { + var q = { + where: { + name: '/' + } + }; + Files.findOne(q) + .then(function(r) { + if(r === null) { var root = { fileId: '1f83f620-c1ed-11e5-9657-7942989daa00', // rootのuuidは固定値 name: '/', parentId: '', fileType: 0 }; - /* - if(process.env.NODE_ENV === 'debug') { - return Files.create(root); - } - */ return Files.create(root); - }) - .then(function() { - var c = { - sayHello: function() { - return test; - }, - getDirectoryParentId: getDirectoryParentId, - getDirectoryId: getDirectoryId, - getDirectory: getDirectory, - existFile: existFile, - notExistFile: notExistFile, - existDirectory: existDirectory, - notExistDirectory: notExistDirectory, - createFile: createFile, - removeFile: removeFile, - createDirectory: createDirectory, - test1: test1, - test2: test2 - /* - removeDirectory: removeDirectory, - getFilename: getFilename, - moveFile: moveFile, - moveDirectory: moveDirectory - */ - }; - resolve(c); - }); + } + }) + .then(function() { + resolve(); }); - } + }); +} - /** - * getDirectoryParentId - * ディレクトリのparentIdを取得する - * @param name - * @returns {promise} ディレクトリが存在すればresolve(uuid), しなければreject - */ - function getDirectoryParentId(name) { - return new Promise(function(resolve, reject) { - var q = { - where: { - name: name, - fileType: 0 - } - }; - Files.findAll(q) - .then(function(r) { - if(r.length === 0) { - reject(new Error('"' + name + '" directory doesn\'t exist.')); - } else { - var map = r.map(function(c) { return c.dataValues.parentId }); - resolve(map); - } - }); +/** + * getDirectoryParentId + * ディレクトリのparentIdを取得する + * @param name + * @returns {promise} ディレクトリが存在すればresolve(uuid), しなければreject + */ +function getDirectoryParentId(name) { + return new Promise(function(resolve, reject) { + var q = { + where: { + name: name, + fileType: 0 + } + }; + Files.findAll(q) + .then(function(r) { + if(r.length === 0) { + reject(new Error('"' + name + '" directory doesn\'t exist.')); + } else { + var map = r.map(function(c) { return c.dataValues.parentId }); + resolve(map); + } }); - } + }); +} + + +/** + * getDirectoryId + * ディレクトリのfileIdを取得する + * @param name + * @returns {promise} ディレクトリが存在すればresolve(uuid), しなければreject + */ + +function getDirectoryId(name) { + return new Promise(function(resolve, reject) { + var q = { + where: { + name: name, + fileType: 0 + } + }; + Files.findAll(q) + .then(function(r) { + if(r.length === 0) { + reject(new Error('"' + name + '" directory doesn\'t exist.')); + } else { + var map = r.map(function(c) { return c.dataValues.fileId }); + resolve(map); + } + }); + }); +} +/** + * getDirectory + * ディレクトリのfileIdを取得する + * @param name + * @returns {promise} ディレクトリが存在すればresolve(name), しなければreject + */ - /** - * getDirectoryId - * ディレクトリのfileIdを取得する - * @param name - * @returns {promise} ディレクトリが存在すればresolve(uuid), しなければreject - */ +function getDirectory(name) { + return new Promise(function(resolve, reject) { + var q = { + where: { + name: name, + fileType: 0 + } + }; + Files.findAll(q) + .then(function(r) { + if(r.length === 0) { + reject(new Error('"' + name + '" directory doesn\'t exist.')); + } else { + var map = r.map(function(c) { return c.dataValues }); + resolve(map); + } + }); + }); +} - function getDirectoryId(name) { - return new Promise(function(resolve, reject) { +/** + * existFile + * 同一ディレクトリに同名のファイルが存在することを確かめる + * @param {string} fileName + * @param {string} parentDirectory parentDirectoryの絶対パス + * @returns {promise} ファイルが存在すればresolve、存在しなければreject + */ +function existFile(fileName, parentDirectory) { + return new Promise(function(resolve, reject) { + existDirectory(parentDirectory) + .catch(function(error) { + reject(error); + }) + .then(function(fileId) { var q = { where: { - name: name, - fileType: 0 + name: fileName, + parentId: fileId } }; - Files.findAll(q) - .then(function(r) { - if(r.length === 0) { - reject(new Error('"' + name + '" directory doesn\'t exist.')); - } else { - var map = r.map(function(c) { return c.dataValues.fileId }); - resolve(map); - } - }); + return Files.findOne(q) + }) + .then(function(r) { + if(r === null) { + reject(new Error("\"" + fileName + "\" does not exist in " + '"' + parentDirectory + "\" directory.")); + } else { + resolve(r.fileId); + } }); - } + }); +} - /** - * getDirectory - * ディレクトリのfileIdを取得する - * @param name - * @returns {promise} ディレクトリが存在すればresolve(name), しなければreject - */ - function getDirectory(name) { - return new Promise(function(resolve, reject) { +/** + * notExistFile + * 同一ディレクトリに同名のファイルが存在していないことを確かめる + * @param {string}fileName + * @param {string}parentDirectory + * @returns {promise} ファイルが存在しなければresolve、存在すればreject + */ +function notExistFile(fileName, parentDirectory) { + return new Promise(function(resolve, reject) { + existDirectory(parentDirectory) + .catch(function(error) { + reject(error); + }) + .then(function(fileId) { var q = { where: { - name: name, - fileType: 0 + name: fileName, + parentId: fileId } }; - Files.findAll(q) - .then(function(r) { - if(r.length === 0) { - reject(new Error('"' + name + '" directory doesn\'t exist.')); - } else { - var map = r.map(function(c) { return c.dataValues }); - resolve(map); - } - }); - }); - } - - /** - * existFile - * 同一ディレクトリに同名のファイルが存在することを確かめる - * @param {string} fileName - * @param {string} parentDirectory parentDirectoryの絶対パス - * @returns {promise} ファイルが存在すればresolve、存在しなければreject - */ - function existFile(fileName, parentDirectory) { - return new Promise(function(resolve, reject) { - existDirectory(parentDirectory) - .catch(function(error) { - reject(error); - }) - .then(function(fileId) { - var q = { - where: { - name: fileName, - parentId: fileId - } - }; - return Files.findOne(q) - }) - .then(function(r) { - if(r === null) { - reject(new Error("\"" + fileName + "\" does not exist in " + '"' + parentDirectory + "\" directory.")); - } else { - //console.log(r.fileId); - resolve(r.fileId); - } - }); + return Files.findOne(q) + }) + .then(function(r) { + if(r === null) { + resolve(); + } else { + reject(new Error("\"" + fileName + "\" has already existed in " + '"' + parentDirectory + "\" directory.")); + } }); - } - + }); +} - /** - * notExistFile - * 同一ディレクトリに同名のファイルが存在していないことを確かめる - * @param {string}fileName - * @param {string}parentDirectory - * @returns {promise} ファイルが存在しなければresolve、存在すればreject - */ - function notExistFile(fileName, parentDirectory) { - return new Promise(function(resolve, reject) { - existDirectory(parentDirectory) - .catch(function(error) { - reject(error); - }) - .then(function(fileId) { - var q = { - where: { - name: fileName, - parentId: fileId - } - }; - return Files.findOne(q) - }) - .then(function(r) { - if(r === null) { - resolve(); - } else { - reject(new Error("\"" + fileName + "\" has already existed in " + '"' + parentDirectory + "\" directory.")); - } - }); - }); - } +/** + * existDirectory + * ディレクトリが存在することを確認する + * @param {string} directory + * @returns {promise} ディレクトリが存在すればresolve{fileId)、存在しなければreject + */ +function existDirectory(directory) { + return new Promise(function(resolve, reject) { + if(!directory) { + reject(new Error('parameter "directory" is undefined')); + } - /** - * existDirectory - * ディレクトリが存在することを確認する - * @param {string} directory - * @returns {promise} ディレクトリが存在すればresolve{fileId)、存在しなければreject - */ - function existDirectory(directory) { - return new Promise(function(resolve, reject) { - if(!directory) { - reject(new Error('parameter "directory" is undefined')); - } + var arrayDirectory; + var root = directory.substr(0,1); - var arrayDirectory; - var root = directory.substr(0,1); + if(root !== '/') { + reject(new Error('directory name should start "/" so that it is absolute path including root.')); + } - if(root !== '/') { - reject(new Error('directory name should start "/" so that it is absolute path including root.')); - } + if(directory === '/') { + resolve('1f83f620-c1ed-11e5-9657-7942989daa00'); // rootのuuid + } else { + arrayDirectory = directory.split('/'); + arrayDirectory.shift(); // root + arrayDirectory.unshift('/'); + } - if(directory === '/') { - resolve('1f83f620-c1ed-11e5-9657-7942989daa00'); // rootのuuid - } else { - arrayDirectory = directory.split('/'); - arrayDirectory.shift(); // root - arrayDirectory.unshift('/'); - } + var directoriesPromise = arrayDirectory.map(function(name) { + return getDirectory(name); + }); - var directoriesPromise = arrayDirectory.map(function(name) { - return getDirectory(name); - }); - Promise.all(directoriesPromise) - .then(function(r) { - var parentId = r[0][0].fileId; - var index; - for(var i=1;i -1) { - parentId = r[i][index].fileId; - } else { - reject(new Error('"' + directory + '" directory doesn\'t exist.')); - } + Promise.all(directoriesPromise) + .then(function(r) { + var parentId = r[0][0].fileId; + var index; + for(var i=1;i -1) { + parentId = r[i][index].fileId; + } else { + reject(new Error('"' + directory + '" directory doesn\'t exist.')); } - resolve(parentId); - }) - .catch(function(error) { - reject(new Error('"' + directory + '" directory doesn\'t exist.')); - }); + } + resolve(parentId); + }) + .catch(function(error) { + reject(new Error('"' + directory + '" directory doesn\'t exist.')); }); - } + }); +} - /** - * notExistDirectory - * ディレクトリが存在しないことを確認する - * @param {string} directory - * @returns {promise} ディレクトリが存在しなければresolve、存在すればreject - */ - function notExistDirectory(directory) { - return new Promise(function(resolve, reject) { - if(!directory) { - resolve(); - } +/** + * notExistDirectory + * ディレクトリが存在しないことを確認する + * @param {string} directory + * @returns {promise} ディレクトリが存在しなければresolve、存在すればreject + */ +function notExistDirectory(directory) { + return new Promise(function(resolve, reject) { + if(!directory) { + resolve(); + } - var arrayDirectory; - var root = directory.substr(0,1); + var arrayDirectory; + var root = directory.substr(0,1); - if(root !== '/') { - resolve(); - } + if(root !== '/') { + resolve(); + } - if(directory === '/') { - reject(new Error('"' + directory + '" directory exists.')); - } else { - arrayDirectory = directory.split('/'); - arrayDirectory.shift(); // root - arrayDirectory.unshift('/'); - } + if(directory === '/') { + reject(new Error('"' + directory + '" directory exists.')); + } else { + arrayDirectory = directory.split('/'); + arrayDirectory.shift(); // root + arrayDirectory.unshift('/'); + } - var directoriesPromise = arrayDirectory.map(function(name) { - return getDirectory(name); - }); - Promise.all(directoriesPromise) - .then(function(r) { - var parentId = r[0][0].fileId; - var index; - for(var i=1;i -1) { - parentId = r[i][index].fileId; - } else { - resolve(); - } - } - reject(new Error('"' + directory + '" directory exists.')); - }) - .catch(function(error) { - resolve(); - }); + var directoriesPromise = arrayDirectory.map(function(name) { + return getDirectory(name); }); - } - - /** - * createFile - * - * @param fileName - * @param parentDirectory - * @returns {promise} - */ - function createFile(fileName,parentDirectory) { - return new Promise(function(resolve, reject) { - if(!fileName) { - reject(new Error('filename is required.')); - } - Promise.all([existDirectory(parentDirectory), notExistFile(fileName, parentDirectory) ]) - .catch(function(error) { - reject(error); - }) - .then(function(r) { - var parentId = r[0] - var q = { - fileId: uuid.v1(), - name: fileName, - parentId: parentId, - fileType: 1 + Promise.all(directoriesPromise) + .then(function(r) { + var parentId = r[0][0].fileId; + var index; + for(var i=1;i -1) { + parentId = r[i][index].fileId; + } else { + resolve(); } - return Files.create(q) - }) - .then(function(r) { - resolve(r.dataValues.fileId); - }); - }); - } - - - /** - * removeFile - * ファイルを削除する - * @param {string} fileName - * @param {string} parentDirectory - * @returns {promise} ファイル削除に成功すればresolve、失敗すればreject - */ - function removeFile(fileName, parentDirectory) { - return new Promise(function(resolve, reject) { - existFile(fileName, parentDirectory) - .catch(function(error) { - reject(error); - }) - .then(function(fileId) { - var q = { - where: { - fileId: fileId - } - }; - return Files.destroy(q); - }) - .then(function() { - resolve(); - }); - }); - } - - /** - * createDirectory - * ディレクトリを作成 - * @param directory - * @returns {promise} ディレクトリの作成に成功すればresolve、失敗すればreject - */ - function createDirectory(directory) { - return new Promise(function(resolve, reject) { - if(!directory) { - reject(new Error('directory name should start "/" so that it is absolute path including root.')); } + reject(new Error('"' + directory + '" directory exists.')); + }) + .catch(function(error) { + resolve(); + }); + }); +} - var leaf = directory.split('/').pop(); - var parentDirectory = directory.replace('/'+leaf, ''); - if(!parentDirectory) { - parentDirectory = '/'; +/** + * createFile + * + * @param fileName + * @param parentDirectory + * @returns {promise} + */ +function createFile(fileName,parentDirectory) { + return new Promise(function(resolve, reject) { + if(!fileName) { + reject(new Error('filename is required.')); + } + Promise.all([existDirectory(parentDirectory), notExistFile(fileName, parentDirectory) ]) + .catch(function(error) { + reject(error); + }) + .then(function(r) { + var parentId = r[0] + var q = { + fileId: uuid.v1(), + name: fileName, + parentId: parentId, + fileType: 1 } - Promise.all([existDirectory(parentDirectory), notExistDirectory(directory), notExistFile(leaf, parentDirectory)]) - .catch(function(error) { - reject(error); - }) - .then(function(r) { - var parentId = r[0]; - var q = { - fileId: uuid.v1(), - name: leaf, - parentId: parentId, - fileType: 0 - } - return Files.create(q) - }) - .then(function(r) { - resolve(r.dataValues.fileId); - }); + return Files.create(q) + }) + .then(function(r) { + resolve(r.dataValues.fileId); }); - } + }); +} - /** - * removeDirectory - * ディレクトリを削除 - * @param directory - * @returns {promise} ディレクトリの削除に成功すればresolve、失敗すればreject - */ - function removeDirectory(directory) { - return new Promise(function(resolve, reject) { - var leaf = directory.split('/').pop(); - var parentDirectory = directory.replace('/'+leaf, ''); - if(!parentDirectory) { - parentDirectory = '/'; - } - Promise.all([existDirectory(parentDirectory), notExistDirectory(directory), notExistFile(leaf, parentDirectory)]) - .catch(function(error) { - reject(error); - }) - .then(function(r) { - var parentId = r[0]; - var q = { - fileId: uuid.v1(), - name: leaf, - parentId: parentId, - fileType: 0 +/** + * removeFile + * ファイルを削除する + * @param {string} fileName + * @param {string} parentDirectory + * @returns {promise} ファイル削除に成功すればresolve、失敗すればreject + */ +function removeFile(fileName, parentDirectory) { + return new Promise(function(resolve, reject) { + existFile(fileName, parentDirectory) + .catch(function(error) { + reject(error); + }) + .then(function(fileId) { + var q = { + where: { + fileId: fileId } - return Files.create(q) - }) - .then(function(r) { - resolve(r.dataValues.fileId); - }); + }; + return Files.destroy(q); + }) + .then(function() { + resolve(); }); - } - - /** - * test1 - * test用にデータベースのレコードを追加する関数 - * @returns {promise} - */ - function test1() { - var q = { - fileId: uuid.v1(), - name: 'hoge.txt', - parentId: '1f83f620-c1ed-11e5-9657-7942989daa00', // rootのuuid - fileType: 1 - }; - return Files.create(q); - } + }); +} - /** - * test2 - * test用にデータベースのレコードを追加する関数 - * @returns {promise} - */ +/** + * createDirectory + * ディレクトリを作成 + * @param directory + * @returns {promise} ディレクトリの作成に成功すればresolve、失敗すればreject + */ +function createDirectory(directory) { + return new Promise(function(resolve, reject) { + if(!directory) { + reject(new Error('directory name should start "/" so that it is absolute path including root.')); + } - function test2() { - var q1 = { - fileId: uuid.v1(), - name: 'one', - parentId: '1f83f620-c1ed-11e5-9657-7942989daa00', // rootのuuid - fileType: 0 - }; - return Files.create(q1) - .then(function() { - var q2 = { + var leaf = directory.split('/').pop(); + var parentDirectory = directory.replace('/'+leaf, ''); + if(!parentDirectory) { + parentDirectory = '/'; + } + Promise.all([existDirectory(parentDirectory), notExistDirectory(directory), notExistFile(leaf, parentDirectory)]) + .catch(function(error) { + reject(error); + }) + .then(function(r) { + var parentId = r[0]; + var q = { fileId: uuid.v1(), - name: 'two', - parentId: q1.fileId, + name: leaf, + parentId: parentId, fileType: 0 + } + return Files.create(q) + }) + .then(function(r) { + resolve(r.dataValues.fileId); + }); + }); +} - }; - return Files.create(q2); + +/** + * removeDirectory + * ディレクトリを削除 + * @param directory + * @returns {promise} ディレクトリの削除に成功すればresolve、失敗すればreject + */ +function removeDirectory(directory) { + return new Promise(function(resolve, reject) { + var leaf = directory.split('/').pop(); + var parentDirectory = directory.replace('/'+leaf, ''); + if(!parentDirectory) { + parentDirectory = '/'; + } + Promise.all([existDirectory(parentDirectory), notExistDirectory(directory), notExistFile(leaf, parentDirectory)]) + .catch(function(error) { + reject(error); }) .then(function(r) { - var q3 = { + var parentId = r[0]; + var q = { fileId: uuid.v1(), - name: 'two', - parentId: '1f83f620-c1ed-11e5-9657-7942989daa00', //rootのuuid + name: leaf, + parentId: parentId, fileType: 0 - }; - return Files.create(q3); + } + return Files.create(q) }) - .then(function() { - var q4 = { - fileId: uuid.v1(), - name: 'hogehoge.txt', - parentId: q1.fileId, - fileType: 1 - }; - return Files.create(q4); + .then(function(r) { + resolve(r.dataValues.fileId); }); - } - + }); +} - /** - * - * @constructor - * @returns {promise} - */ - - /** - * productionモード時は、db.workspaceを永続化させる - * DEBUGモードの時は、db.debugを実行毎に作成する。 - * DEBUGモードの時は、sync()の中で、/レコードがFilesテーブルに追加される。 - * モードの切り替えは環境変数NODE_ENVで行っている。 - * zephyr serveコマンドが実行されるとNODE_ENV = 'production' - * zephyr debugコマンドが実行されるとNODE_ENV = 'debug' - * となる。 - * それぞれの設定は$ZEOHYR_HOME/cli/zephyr-serve, $ZEPHYR_HOME/zephyre_debugを参照 - */ - - var dbPath; - var dbOption = { - dialect: 'sqlite' +/** + * test1 + * test用にデータベースのレコードを追加する関数 + * @returns {promise} + */ +function test1() { + var q = { + fileId: uuid.v1(), + name: 'hoge.txt', + parentId: '1f83f620-c1ed-11e5-9657-7942989daa00', // rootのuuid + fileType: 1 }; + return Files.create(q); +} - if(process.env['NODE_ENV'] === 'production') { - dbPath = __dirname + '/../../user-specific-files/db/db.workspace'; - // if doesn't exist workspace.db, create. - try { - fs.accessSync(dbPath, fs.R_OK | fs.W_OK); - } catch(e) { - fs.writeFileSync(dbPath, ''); - } - dbOption.storage = dbPath; - - } else if(process.env['NODE_ENV'] === 'debug') { - dbPath = __dirname + '/../../user-specific-files/db/db.debug'; - try { - fs.accessSync(dbPath, fs.R_OK | fs.W_OK); - fs.unlinkSync(dbPath); - } catch(e) { - } - - fs.writeFileSync(dbPath, ''); - dbOption.storage = dbPath; - } - +/** + * test2 + * test用にデータベースのレコードを追加する関数 + * @returns {promise} + */ +function test2() { + var q1 = { + fileId: uuid.v1(), + name: 'one', + parentId: '1f83f620-c1ed-11e5-9657-7942989daa00', // rootのuuid + fileType: 0 + }; + return Files.create(q1) + .then(function() { + var q2 = { + fileId: uuid.v1(), + name: 'two', + parentId: q1.fileId, + fileType: 0 - sequelize = new Sequelize('','','', dbOption); - - var Files = sequelize.define('file', { - fileId: { - type: Sequelize.UUID, - field: 'file_id', - primaryKey: true - }, - name: { - type: Sequelize.STRING, - field: 'name', - allowNull: false - }, - parentId: { - type: Sequelize.UUID, - field: 'parent_id', - allowNull: false - }, - fileType: { - type: Sequelize.ENUM(0,1), - field: 'file_type', - allowNull: false - } + }; + return Files.create(q2); + }) + .then(function(r) { + var q3 = { + fileId: uuid.v1(), + name: 'two', + parentId: '1f83f620-c1ed-11e5-9657-7942989daa00', //rootのuuid + fileType: 0 + }; + return Files.create(q3); + }) + .then(function() { + var q4 = { + fileId: uuid.v1(), + name: 'hogehoge.txt', + parentId: q1.fileId, + fileType: 1 + }; + return Files.create(q4); }); - - return sync(); } -module.exports = DB; +module.exports = { instance: instance }; diff --git a/server/class/Eos.js b/server/class/Eos.js index 347aaf1..1387219 100644 --- a/server/class/Eos.js +++ b/server/class/Eos.js @@ -4,266 +4,264 @@ * @returns {object} * function execute(command, params) { */ -function Eos() { - - /** - * - * Class variables - */ - - // include all Eos command's info. - // For seaching with O(n), the object key name is command name. - var commandReference = { - mrcImageInfo: { }, - dcdFilePrint: { } +var eos = { + validate: validate, + toExecString: toExecString, + execute: execute +} + + +/** + * + * Class variables + */ + +// include all Eos command's info. +// For seaching with O(n), the object key name is command name. +var commandReference = { + mrcImageInfo: { }, + dcdFilePrint: { } +}; + +// for unit test +var workspace = ['file1.txt', 'file2.txt']; + + +/** + * + * Class variables + */ + + +/** + * validate + * コマンドとオプションのバリデーション + * @param command + * @param params + * @returns {valid: boolean, message: string} + */ +function validate(command, options) { + var result = { hasDone: false, // true | false + comment: ''// string }; - // for unit test - var workspace = ['file1.txt', 'file2.txt']; - - - /** - * - * Class variables - */ - - - /** - * validate - * コマンドとオプションのバリデーション - * @param command - * @param params - * @returns {valid: boolean, message: string} - */ - function validate(command, options) { - var result = { hasDone: false, // true | false - comment: ''// string - }; - - var ocf; // Array - var ocfObj = {}; // key-value - - try { - /** - * Check of command name - */ - if(typeof command !== 'string') { - errorMsg = 'Command parameter need to be string'; - throw new Error(errorMsg); - } + var ocf; // Array + var ocfObj = {}; // key-value - var hasCommand = Object.keys(commandReference).indexOf(command) > -1; - if(!hasCommand) { - errorMsg = 'Command name is invalid'; - throw new Error(errorMsg); - } + try { + /** + * Check of command name + */ + if(typeof command !== 'string') { + errorMsg = 'Command parameter need to be string'; + throw new Error(errorMsg); + } - /** - * Check of options - */ + var hasCommand = Object.keys(commandReference).indexOf(command) > -1; + if(!hasCommand) { + errorMsg = 'Command name is invalid'; + throw new Error(errorMsg); + } - if(!(Array.isArray(options))) { - errorMsg = 'Options need to be Array'; - throw new Error(errorMsg); - } + /** + * Check of options + */ + + if(!(Array.isArray(options))) { + errorMsg = 'Options need to be Array'; + throw new Error(errorMsg); + } - if(options.length === 0) { - errorMsg = 'At least one option is required.'; - throw new Error(errorMsg); - } + if(options.length === 0) { + errorMsg = 'At least one option is required.'; + throw new Error(errorMsg); + } - // translate options to key-value and check whether options include correct member - var optionsObj = {}; - var hasCorrectMember = true; - var isArgumentsArray = true; + // translate options to key-value and check whether options include correct member + var optionsObj = {}; + var hasCorrectMember = true; + var isArgumentsArray = true; - options.forEach(function(o) { - if(!(o.name) && !(o.arguments)) { - hasCorrectMember = false; + options.forEach(function(o) { + if(!(o.name) && !(o.arguments)) { + hasCorrectMember = false; + } else { + if(Array.isArray(o.arguments)) { + optionsObj[o.name] = o.arguments; } else { - if(Array.isArray(o.arguments)) { - optionsObj[o.name] = o.arguments; - } else { - isArgumentsArray = false; - } + isArgumentsArray = false; } - }); - - // check each object has proberties "name" and "argumets" - if(!hasCorrectMember) { - errorMsg = 'Options need to include Object which have properties "name" and "arguments"'; - throw new Error(errorMsg); } + }); - // check each "argumets" properties is Array - if(!isArgumentsArray) { - errorMsg = 'Each "arguments" properties needs to be Array'; - throw new Error(errorMsg); - } + // check each object has proberties "name" and "argumets" + if(!hasCorrectMember) { + errorMsg = 'Options need to include Object which have properties "name" and "arguments"'; + throw new Error(errorMsg); + } - // Read OptionControlFile info of command - ocf = require(__dirname + '/../../user-specific-files/OptionControlFile/commands/' + command); + // check each "argumets" properties is Array + if(!isArgumentsArray) { + errorMsg = 'Each "arguments" properties needs to be Array'; + throw new Error(errorMsg); + } - // translate ocf info to key-value - var notIncludingRequiredOptions = []; - ocf.forEach(function(o) { - if(o.optionProperties && Object.keys(optionsObj).indexOf(o.option) < 0) { - notIncludingRequiredOptions.push(o.option); - } - ocfObj[o.option] = o; - }); + // Read OptionControlFile info of command + ocf = require(__dirname + '/../../user-specific-files/OptionControlFile/commands/' + command); - // check whether all required option exist - if(notIncludingRequiredOptions.length > 0) { - errorMsg = 'Option ' + notIncludingRequiredOptions.toString() + ' are required'; - throw new Error(errorMsg); + // translate ocf info to key-value + var notIncludingRequiredOptions = []; + ocf.forEach(function(o) { + if(o.optionProperties && Object.keys(optionsObj).indexOf(o.option) < 0) { + notIncludingRequiredOptions.push(o.option); } + ocfObj[o.option] = o; + }); - var invalidArgumentsNumber= []; - var invalidArgumentType = []; - var invalidOutputFileName = []; + // check whether all required option exist + if(notIncludingRequiredOptions.length > 0) { + errorMsg = 'Option ' + notIncludingRequiredOptions.toString() + ' are required'; + throw new Error(errorMsg); + } - // output file Regexp - var outRegExp = /out|append/; + var invalidArgumentsNumber= []; + var invalidArgumentType = []; + var invalidOutputFileName = []; - options.forEach(function(o) { - // option number - var expectNum = ocfObj[o.name].optionNumber; - var actualNum = o.arguments.length; - if(expectNum !== actualNum) { - invalidArgumentsNumber.push({name: o.name, expect: expectNum, actual: actualNum}); - } + // output file Regexp + var outRegExp = /out|append/; + options.forEach(function(o) { + // option number + var expectNum = ocfObj[o.name].optionNumber; + var actualNum = o.arguments.length; + if(expectNum !== actualNum) { + invalidArgumentsNumber.push({name: o.name, expect: expectNum, actual: actualNum}); + } - // argType and outFile name - o.arguments.forEach(function(arg,i) { - // argType - var formType = ocfObj[o.name].arg[i].formType - if(formType === 'select') { // This argument is filename - var exist = workspace.indexOf(arg) > -1; - if(!exist) { - invalidArgumentType.push({name: o.name, file: arg}); - } - } else { - var expectType = formType === 'text' ? 'string' : 'number'; - var actualType = typeof arg; - if(expectType !== actualType) { - invalidArgumentType.push({name: o.name, expect: expectType, actual: actualType}); - } + + // argType and outFile name + o.arguments.forEach(function(arg,i) { + // argType + var formType = ocfObj[o.name].arg[i].formType + if(formType === 'select') { // This argument is filename + var exist = workspace.indexOf(arg) > -1; + if(!exist) { + invalidArgumentType.push({name: o.name, file: arg}); + } + } else { + var expectType = formType === 'text' ? 'string' : 'number'; + var actualType = typeof arg; + if(expectType !== actualType) { + invalidArgumentType.push({name: o.name, expect: expectType, actual: actualType}); } + } - // outFile name - if(outRegExp.test(ocfObj[o.name].arg[i].argType)) { - if(workspace.indexOf(o.arguments[i]) > -1) { - invalidOutputFileName.push({name: o.name, file: arg}); - } + // outFile name + if(outRegExp.test(ocfObj[o.name].arg[i].argType)) { + if(workspace.indexOf(o.arguments[i]) > -1) { + invalidOutputFileName.push({name: o.name, file: arg}); } - }); + } }); + }); - // check arguments number value - if(invalidArgumentsNumber.length > 0) { - errorMsg = '"arguments" properties is invalid number.\n'; - invalidArgumentsNumber.forEach(function(i) { - errorMsg += i.name + ' expect to ' + i.expect + ', but actual ' + i.actual + '.\n'; - }); - throw new Error(errorMsg); - } + // check arguments number value + if(invalidArgumentsNumber.length > 0) { + errorMsg = '"arguments" properties is invalid number.\n'; + invalidArgumentsNumber.forEach(function(i) { + errorMsg += i.name + ' expect to ' + i.expect + ', but actual ' + i.actual + '.\n'; + }); + throw new Error(errorMsg); + } - // check arguments type - if(invalidArgumentType.length > 0) { - errorMsg = '"arguments" type is invalid.\n'; - invalidArgumentType.forEach(function(i) { - if(i.file) { - errorMsg += i.name + ' ' + i.file + ' does not exist.\n'; - } else { - errorMsg += i.name + ' expect to ' + i.expect + ', but actual ' + i.actual + '.\n'; - } - }); - throw new Error(errorMsg); - } + // check arguments type + if(invalidArgumentType.length > 0) { + errorMsg = '"arguments" type is invalid.\n'; + invalidArgumentType.forEach(function(i) { + if(i.file) { + errorMsg += i.name + ' ' + i.file + ' does not exist.\n'; + } else { + errorMsg += i.name + ' expect to ' + i.expect + ', but actual ' + i.actual + '.\n'; + } + }); + throw new Error(errorMsg); + } - // check outFile name - if(invalidOutputFileName.length > 0) { - errorMsg = 'output file name is invalid.\n'; - invalidOutputFileName.forEach(function(i) { - errorMsg += i.name + ' ' + i.file + ' has already existed.\n'; - }); - throw new Error(errorMsg); - } - } catch(e) { - result.message = e.message; - return result; + // check outFile name + if(invalidOutputFileName.length > 0) { + errorMsg = 'output file name is invalid.\n'; + invalidOutputFileName.forEach(function(i) { + errorMsg += i.name + ' ' + i.file + ' has already existed.\n'; + }); + throw new Error(errorMsg); } + } catch(e) { + result.message = e.message; + return result; } +} - /** - * toExecString - * - * @param command - * @param options - * @returns {string} - */ - function toExecString(command, options) { - var ocf = require(__dirname + '/../../user-specific-files/OptionControlFile/commands/' + command); // Array - var finalOptions = {}; - var execStr = command + ' '; - - // set default parameters - ocf.forEach(function(o) { +/** + * toExecString + * + * @param command + * @param options + * @returns {string} + */ +function toExecString(command, options) { + var ocf = require(__dirname + '/../../user-specific-files/OptionControlFile/commands/' + command); // Array + var finalOptions = {}; + var execStr = command + ' '; + + // set default parameters + ocf.forEach(function(o) { o.arg.forEach(function(arg) { - if(!(arg.initialValue === "") && arg.initialValue) { + if(!(arg.initialValue === "") && arg.initialValue) { if(!(finalOptions[o.option])) { - finalOptions[o.option] = []; - finalOptions[o.option].push(arg.initialValue); + finalOptions[o.option] = []; + finalOptions[o.option].push(arg.initialValue); } else { - finalOptions[o.option].push(arg.initialValue); + finalOptions[o.option].push(arg.initialValue); } - } + } + }); }); - }); - // set user setting parameters - options.forEach(function(o) { + // set user setting parameters + options.forEach(function(o) { finalOptions[o.name] = o.arguments; - }); + }); - // set execution string - Object.keys(finalOptions).forEach(function(key) { + // set execution string + Object.keys(finalOptions).forEach(function(key) { execStr += key + ' '; finalOptions[key].forEach(function(arg) { - execStr += arg + ' '; + execStr += arg + ' '; + }); }); - }); - // remove last blank - execStr = execStr.slice(0,execStr.length-1); - - return execStr; - } + // remove last blank + execStr = execStr.slice(0,execStr.length-1); + return execStr; +} - return { - /** - * execute - * - * @param command - * @param params - * @returns {object} - */ - execute: function(command, options) { - var result = validate(command, options); - if(!result.hasDone) { - } else { - var str = toExecString(command, options); - } - }, - // For unit test - validate: validate, - toExecString: toExecString +/** + * execute + * + * @param command + * @param params + * @returns {object} + */ +function execute(command, options) { + var result = validate(command, options); + if(!result.hasDone) { + } else { + var str = toExecString(command, options); } } -module.exports = Eos; +module.exports = { instance: eos }; diff --git a/test/mocha/DB.test.js b/test/mocha/DB.test.js index 09cbfe1..d3e6863 100644 --- a/test/mocha/DB.test.js +++ b/test/mocha/DB.test.js @@ -1,16 +1,12 @@ (function() { 'use strict'; - var DB = require('../../server/class/DB'); + var db = require('../../server/class/DB').instance; var chai = require('chai'); var chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); var expect = chai.expect; chai.should(); - //process.env['NODE_ENV'] = 'production'; - - - describe('DB クラス', function() { var constructor = ` @@ -23,15 +19,9 @@ */ `; describe(constructor, function() { - var db; before(function() { - return DB() - .then(function(r) { - db = r; - }); + return db.init() }); - - it('should return hello when call sayHello', function() { expect(db.sayHello()).to.equal('hello'); }); @@ -47,12 +37,8 @@ */ `; describe(getDirectoryParentId, function() { - var db; before(function() { - return DB() - .then(function(r) { - db = r; - }) + return db.init() .then(function() { return db.test2(); }); @@ -67,7 +53,6 @@ it('should be rejected when \'two\' exists', function() { return expect(db.getDirectoryParentId('two')).to.eventually.have.length(2); }); - }); var getDirectoryId = ` @@ -79,17 +64,12 @@ */ `; describe(getDirectoryId, function() { - var db; before(function() { - return DB() - .then(function(r) { - db = r; - }) + return db.init() .then(function() { return db.test2(); }); }); - it('should be rejected when a directory does not exist', function() { return db.getDirectoryId('hoge').should.be.rejectedWith(Error, '"hoge" directory doesn\'t exist.'); }); @@ -99,7 +79,6 @@ it('should be rejected when \'two\' exists', function() { return expect(db.getDirectoryId('two')).to.eventually.have.length(2); }); - }); @@ -111,13 +90,9 @@ * @returns {promise} ディレクトリが存在すればresolve(obj), しなければreject */ `; - describe(getDirectoryId, function() { - var db; + describe(getDirectory, function() { before(function() { - return DB() - .then(function(r) { - db = r; - }) + return db.init() .then(function() { return db.test2(); }); @@ -132,7 +107,6 @@ it('should be rejected when \'two\' exists', function() { return expect(db.getDirectory('two')).to.eventually.have.length(2); }); - }); @@ -146,12 +120,8 @@ */ `; describe(existFile, function() { - var db; before(function() { - return DB() - .then(function(r) { - db = r; - }) + return db.init() .then(function() { return db.test1(); }) @@ -169,7 +139,6 @@ it('should be resolved when file exists in a directory', function() { return expect(db.existFile('hogehoge.txt', '/one')).to.eventually.be.a('string'); }); - }); @@ -184,12 +153,8 @@ */ `; describe(notExistFile, function() { - var db; before(function() { - return DB() - .then(function(r) { - db = r; - }) + return db.init() .then(function() { return db.test1(); }) @@ -207,7 +172,6 @@ it('should be resolved when the same name file does not exist in directory', function() { return expect(db.notExistFile('hoge.txt', '/one')).to.eventually.equal(); }); - }); var existDirectory = ` @@ -219,12 +183,8 @@ */ `; describe(existDirectory, function() { - var db; before(function() { - return DB() - .then(function(r) { - db = r; - }) + return db.init() .then(function() { return db.test2(); }) @@ -260,12 +220,8 @@ */ `; describe(existDirectory, function() { - var db; before(function() { - return DB() - .then(function(r) { - db = r; - }) + return db.init() .then(function() { return db.test1(); }) @@ -289,7 +245,6 @@ it('should be resolved(2)', function() { return expect(db.notExistDirectory('hoge')).to.eventually.equal(); }); - }); @@ -303,12 +258,8 @@ */ `; describe(createFile, function() { - var db; before(function() { - return DB() - .then(function(r) { - db = r; - }) + return db.init() .then(function() { return db.test1(); }) @@ -335,7 +286,6 @@ it('should be rejected(3)', function() { return db.createFile(null, '/').should.be.rejectedWith(Error, 'filename is required.'); }); - }); @@ -350,12 +300,8 @@ `; describe(removeFile, function() { - var db; before(function() { - return DB() - .then(function(r) { - db = r; - }) + return db.init() .then(function() { return db.test1(); }); @@ -379,12 +325,8 @@ */ `; describe(createDirectory, function() { - var db; before(function() { - return DB() - .then(function(r) { - db = r; - }) + return db.init() .then(function() { return db.test1(); }) @@ -394,11 +336,6 @@ .then(function() { return db.createDirectory('/one/hoge'); }); - /* - .then(function() { - return db.createDirectory('/one/two/three'); - }); - */ }); it('should be rejected when directory has already existed', function() { @@ -419,8 +356,6 @@ it('should be rejected(2)', function() { return db.createDirectory().should.be.rejectedWith(Error, 'directory name should start "/" so that it is absolute path including root.'); }); - }); - }); })(); diff --git a/test/mocha/Eos.test.js b/test/mocha/Eos.test.js index 2095365..bac5c7f 100644 --- a/test/mocha/Eos.test.js +++ b/test/mocha/Eos.test.js @@ -1,6 +1,6 @@ (function() { 'use strict'; - var Eos = require('../../server/class/Eos'); + var eos = require('../../server/class/Eos').instance; var expect = require('chai').expect; var test1 = ` @@ -25,9 +25,7 @@ `; describe('Eos クラス', function() { - var eos; before(function() { - eos = new Eos(); }); describe(test1, function() { -- 2.11.0