warrior-code-api
Version:
API for Warrior-Code.
71 lines (52 loc) • 1.63 kB
JavaScript
;
const fs = require('fs');
const path = require('path');
const config = require('config');
const mongoose = require('mongoose');
const MAPS_DIR = process.env.WARRIORJS_MAPS_DIR || path.join(__dirname, '..', 'maps');
// Initialize the connection to MongoDB.
mongoose.connect(`${config.get('MongoDB.uri')}/${config.get('MongoDB.dbName')}`);
console.log(`Database running at: ${config.get('MongoDB.uri')}/${config.get('MongoDB.dbName')}`);
const Map = require('../models/Map');
//
// TODO: Promisify this...
//
Map.count((err, count) => {
let mapsCheck = 0;
console.log(`There are ${count} maps in the system before the update.`);
console.log();
// Read all the maps on the `maps` directory.
let files = fs.readdirSync(MAPS_DIR);
console.log(`There are ${files.length} maps in the maps directory.`);
console.log(`(MAPS_DIR: ${MAPS_DIR})`);
console.log();
const ifDoneExit = () => {
if (mapsCheck >= files.length) {
Map.count((err, count) => {
console.log(`There are ${count} maps in the system after the update.`);
console.log();
process.exit();
});
}
}
// Check if the map exists in the database.
for (let file of files) {
Map.findOne({dataFile: file}, (err, map) => {
if (map) {
mapsCheck += 1;
return ifDoneExit();
}
// If the map does not exists. Create it.
map = new Map({
world: 'demo',
dataFile: file,
name: file.split('.')[0]
});
map.save((err, map) => {
mapsCheck += 1;
ifDoneExit();
});
});
}
// process.exit();
});