UNPKG

@eyugame/dao

Version:

A modelling tool for RealtimeDatabase(firebase) & Dynamodb(Amazon) & Redis

335 lines (302 loc) 10 kB
'use strict'; const daoutils = require('../utils'); //----------------------------------------FIREBASE---------------------------------------- // npm install firebase-admin --save-dev // const admin = require('firebase-admin'); // const serviceAccount = require('../../firebase-key.json'); // admin.initializeApp({ // credential: admin.credential.cert(serviceAccount), // databaseURL: "https://hello-fb-go.firebaseio.com" // }); // daoutils.setupDB({ // db: 'firebase', // tablePrefix: 'books' // }); //----------------------------------------FIREBASE---------------------------------------- //----------------------------------------DYNAMODB---------------------------------------- // npm install dynamodb --save-dev const AWS = require('aws-sdk'); const dbUrl = 'http://localhost:8000'; const awsConfig = { accessKeyId: 'test', secretAccessKey: 'test-secret', region: 'test-region', endpoint: dbUrl, } AWS.config.update(awsConfig); daoutils.setupDB({ db: 'aws', tablePrefix: 'books', throughput: { readCapacity: 0, writeCapacity: 0 } }) //----------------------------------------DYNAMODB---------------------------------------- //----------------------------------------REDIS---------------------------------------- // npm install redis --save-dev // daoutils.setupDB({ // db: 'redis', // host: 'localhost', // port: 6379, // tablePrefix: 'books', // // password: '123321' // }); //----------------------------------------REDIS---------------------------------------- const joi = require('joi'); const expect = require('chai').expect; const dao = require('../index'); global.DEBUG = true; dao.init(); const User = dao.define('users', { hashKey: 'id', //rangeKey: 'platform', schema: { id: joi.string().required(), name: joi.string(), age: joi.number().default(18) }, tableName: 'test_users', FIREBASE_IGNORED: ['id'], methods: {} }); const Book = dao.define('books', { hashKey: 'isbn', rangeKey: 'author', schema: { isbn: joi.string().required(), author: joi.string().required(), title: joi.string().required() }, tableName: 'books', FIREBASE_IGNORED: ['isbn', 'author'], methods: { toVO() { const result = {}; Object.assign(result, this._entity); return result; } } }); const id = 'hp'; const idSnape = 'snape'; describe('#Entity', function () { //dynamodb first time, need create tables before(async function () { if (daoutils.isAWSPlatform()) { //first time, need manual create tables const dynamodb = require('dynamodb'); await dynamodb.createTables({ 'users': DAO_CONFIG.throughput, 'books': DAO_CONFIG.throughput }); console.log(`................Create all tables success................`); } }); it('LoadOrCreate', function (done) { const testUserId = Date.now().toString(); User.loadOrCreate({ id: testUserId }, () => { return { id: testUserId, name: 'test user' } }).then(entity => { console.log('loadOrCreate:::', entity.toVO()); expect(entity.toVO()).to.deep.equal({ name: 'test user', age: 18 }) done(); }).catch(err => done(err)); }); it('Create', function (done) { User.create({ id: idSnape, name: 'Severus Snape' }).then(entity => { console.log('Create:::', entity.toVO()); done(); }).catch(err => done(err)); }) it('Update with transaction', function (done) { new Promise(async (resolve, reject) => { try { const testId = 'Dumbledore'; let entity = await User.loadOrCreate({ id: testId, name: 'Dumbledore', age: 71 }); console.log('Update with transaction, loadOrCreate:::', entity); entity = await User.load({ id: testId }); let updateData = { id: testId, age: 101 }; //need copy db version!!!!!!!!! User.copyAttrVersion(updateData, entity); await User.update(updateData, { transaction: true }); let updateEntity = await User.load({ id: testId }); console.log('Update before:::', entity, ' , after:', updateEntity); resolve(); } catch (err) { reject(err); } }).then(() => done()).catch(err => done(err)); }); it('Update without transaction', function (done) { const testId = 'Hagrid'; let updateData = { id: testId, name: 'Hagrid', age: 50 }; User.update(updateData).then(async () => { let updateEntity = await User.load({ id: testId, }); console.log('Update:::', updateEntity); done(); }).catch(err => done(err)); }); it('Exists & Destroy', function (done) { User.exists({ id: idSnape }).then(exists => { console.log('Exist:::', exists); if (exists) { User.destroy({ id: idSnape }).then(() => { console.log('Destroy success'); done() }).catch(err => { done(err); }) } }).catch(err => done(err)); }); it('Alter(atomic)', function (done) { User.alter({ id }, { age: 1 }).then(entity => { User.alter({ id }, { age: 1 }).then(entity2 => { console.log('After alter:::', entity, ' ,alter2:', entity2); done(); }).catch(err => done(err)); }).catch(err => done(err)); }) it('listAll & batchGet', function (done) { new Promise(async (resolve, reject) => { const author = 'JK-Rowling'; const isbn1 = '00001'; const isbn2 = '00002'; const isbn3 = '00003'; try { await Book.loadOrCreate({ isbn: isbn1, author }, () => { return { isbn: isbn1, author, title: 'Harry Potter and the Philosopher\'s Stone' } }) await Book.loadOrCreate({ isbn: isbn2, author, }, () => { return { isbn: isbn2, author, title: 'Harry Potter and the Chamber of Secrets' } }) await Book.loadOrCreate({ isbn: isbn3, author, }, () => { return { isbn: isbn3, author, title: 'Harry Potter and the Prisoner of Azkaban' } }) let books = await Book.listAll(author); for (let e of books) { console.log('ListAll:::', e.toVO()) } //expect(books.length).to.equal(3); const keys = [{ isbn: isbn1, author }, { isbn: isbn2, author }] books = await Book.batchGet(keys); for (let e of books) { console.log('RangeKey BatchGet:::', e.toVO()) } expect(books.length).to.equal(keys.length); let wizards = await User.batchGet(['hp', 'Dumbledore']); for (let e of wizards) { console.log('Only HashKey BatchGet:::', e.toVO()) } //expect(wizards.length).to.equal(2); resolve(); } catch (err) { reject(err); } }).then(() => done()).catch(err => done(err)); }); it('Save & Remove', function (done) { const testId = 't' + Date.now(); new Promise(async (resolve, reject) => { try { let entity = await User.loadOrCreate({ id: testId }, () => { return { id: testId, name: 'test save & remove', age: 0 } }); entity.age = 1; await entity.save({ transaction: true }); console.log('After save with transaction:::', entity); entity.age = 2; await entity.save(); console.log('After save without transaction:::', entity); console.log('before load.........................'); await entity.remove(); let removeEntity = await User.load({ id: testId }); console.log('Remove entity:::', removeEntity); expect(removeEntity).to.equal(null); resolve(); } catch (err) { reject(err); } }).then(() => done()).catch(err => done(err)); }) });