Skip to content

Commit

Permalink
refactoring storage layout
Browse files Browse the repository at this point in the history
added localstorage to schema
  • Loading branch information
Awhiteweb committed Jun 12, 2023
1 parent 0df2b32 commit 9ca439b
Show file tree
Hide file tree
Showing 5 changed files with 148 additions and 19 deletions.
55 changes: 55 additions & 0 deletions Projects/Local-Storage/SA/Globals/Persistence.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
* @typedef {{
* initialize: initialize,
* finalize: finalize,
* saveItem: saveItem,
* saveAll: saveAll,
* deleteItem: deleteItem,
* deleteAll: deleteAll,
* findItem: findItem,
* findMany: findMany,
* }} PersistenceModel
*/

/**
* Returns a function the creates a new persistence store matching the storeType
* (file, mongodb) with the name being either
* the file path for files or database name for a database
* @returns {{
* newPersistenceStore: (storeType: string, name: string) => Promise<PersistenceModel>
* }}
*/
exports.newLocalStorageGlobalsPersistence = function newLocalStorageGlobalsPersistence() {
const thisObject = {
newPersistenceStore: newPersistenceStore
}

let databaseRepositories = undefined

return thisObject

/**
* Returns a new implementation of the chosen data store,
* if the storeType does not match any of the current
* implementations then an error is thrown.
*
* @param {string} storeType
* @param {string} name
*/
async function newPersistenceStore(storeType, name) {
switch (storeType) {
case 'file':
return require('../Modules/FileStore').newNetworkGlobalsStoresFileStore(name)
case 'database':
return await getDatabaseRepositories().getRepository(name)
default: throw new Error('The store type ' + storeType + ' is not implemented, why not create it yourself.')
}
}

function getDatabaseRepositories() {
if(databaseRepositories === undefined) {
databaseRepositories = SA.projects.internalStorage.modules.databaseRepositories()
}
return databaseRepositories
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ const { Pool } = require('pg')
*/

/**
*
* @returns
* @returns {DbContext}
*/
exports.newDbContext = function newDbContext() {
thisObject = {
Expand Down
53 changes: 53 additions & 0 deletions Projects/Local-Storage/SA/Modules/DatabaseRepositories.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/**
*
* @returns {{
* getRepository: (name: string) => import('../Globals/Persistence').PersistenceModel
* }}
*/
exports.newDatabaseRepositories = function newDatabaseRepositories() {
const thisObject = {
getRepository: getRepository
}

/**
* This property should only be accessed using the getDbContext function
* as it will operate as a singleton for all the repositories and only be
* initialized when first required
*
* @type {import('../Internal/DbContext').DbContext}
*/
let privateDbContext = undefined

return thisObject


async function getRepository(name) {
switch (name) {
case 'UserBalances':
const repo = require('../Repositories/UserBalanceRepository').newUserBalanceRepository(await getDbContext())
await repo.initialize()
return repo
default:
throw new Error('The database repository ' + name + ' is not implemented, why not create it yourself.')

}
}

/**
*
* @returns {Promise<import('../Internal/DbContext').DbContext>}
*/
async function getDbContext() {
if (privateDbContext === undefined) {
privateDbContext = require('../Internal/DbContext').newDbContext()
return await privateDbContext.intialize({
databse: global.env.DATABASE.name,
host: global.env.DATABASE.host,
password: global.env.DATABASE.password,
port: global.env.DATABASE.port,
user: global.env.DATABASE.username,
}).then(() => privateDbContext)
}
return privateDbContext
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
* }} UserItem
*/

exports.newUserBalanceRepository = function newUserBalanceRepository() {
/**
* @param {import('../Internal/DbContext').DbContext}
*/
exports.newUserBalanceRepository = function newUserBalanceRepository(dbContext) {
const thisObject = {
TABLE_NAME: () => 'user-balances',
intialize: intialize,
initialize: intialize,
saveItem: saveItem,
saveAll: saveAll,
deleteItem: deleteItem,
Expand All @@ -19,10 +21,7 @@ exports.newUserBalanceRepository = function newUserBalanceRepository() {
findMany: findMany,
}

/**
* @type {import('../Globals/DbContext').DbContext}
*/
let thisDbContext = undefined
const TABLE_NAME = 'user-balances'
const structure = {
id: {
name: 'id',
Expand Down Expand Up @@ -50,10 +49,10 @@ exports.newUserBalanceRepository = function newUserBalanceRepository() {

/**
*
* @param {import('../Globals/DbContext').DbContext} dbContext
* @param {import('../Internal/DbContext').DbContext} dbContext
* @returns {Promise<void>}
*/
async function intialize(dbContext) {
async function intialize() {
thisDbContext = dbContext
await createTable()
}
Expand All @@ -62,7 +61,7 @@ exports.newUserBalanceRepository = function newUserBalanceRepository() {
const columns = Object.keys(structure)
.map(key => `${structure[key].name} ${structure[key].type} ${structure[key].params.join(' ')}`)
.join(',')
const query = `CREATE TABLE [IF NOT EXISTS] ${thisObject.TABLE_NAME()} (${columns});`
const query = `CREATE TABLE [IF NOT EXISTS] ${thisObject.TABLE_NAME} (${columns});`
await thisDbContext.execute(query)
}

Expand All @@ -72,7 +71,7 @@ exports.newUserBalanceRepository = function newUserBalanceRepository() {
*/
async function saveItem(item) {
const query = `
INSERT INTO ${thisObject.TABLE_NAME()}(${structure.id.name}, ${structure.name.name}, ${structure.balance.name}, ${structure.updateAt.name})
INSERT INTO ${thisObject.TABLE_NAME}(${structure.id.name}, ${structure.name.name}, ${structure.balance.name}, ${structure.updateAt.name})
VALUES (${item.id}, ${item.name}, ${item.balance}, ${item.updateAt})
RETURNING ${structure.id.name}`
return await thisDbContext.execute(query)
Expand All @@ -85,7 +84,7 @@ exports.newUserBalanceRepository = function newUserBalanceRepository() {
async function saveAll(items) {
const values = items.map(item => `(${item.id}, ${item.name}, ${item.balance}, ${item.updateAt})`).join(',')
const query = `
INSERT INTO ${thisObject.TABLE_NAME()}(${structure.id.name}, ${structure.name.name}, ${structure.balance.name}, ${structure.updateAt.name})
INSERT INTO ${thisObject.TABLE_NAME}(${structure.id.name}, ${structure.name.name}, ${structure.balance.name}, ${structure.updateAt.name})
VALUES ${values}
RETURNING ${structure.id.name}`
return await thisDbContext.execute(query)
Expand All @@ -100,15 +99,15 @@ exports.newUserBalanceRepository = function newUserBalanceRepository() {
*/
async function deleteItem(item) {
const where = `${structure[item.key]} = ${item.value}`
const query = `DELETE FROM ${thisObject.TABLE_NAME()} WHERE ${where}`
const query = `DELETE FROM ${thisObject.TABLE_NAME} WHERE ${where}`
return await thisDbContext.execute(query)
}

/**
* @returns {Promise<void>}
*/
async function deleteAll() {
return await thisDbContext.execute(`TRUNCATE TABLE ${thisObject.TABLE_NAME()}`)
return await thisDbContext.execute(`TRUNCATE TABLE ${thisObject.TABLE_NAME}`)
}

/**
Expand All @@ -124,11 +123,12 @@ exports.newUserBalanceRepository = function newUserBalanceRepository() {
? propertiesToReturn.map(key => structure[key].name).join(',')
: '*'
const where = `${structure[item.key]} = ${item.value}`
const query = `SELECT ${properties} FROM ${thisObject.TABLE_NAME()} WHERE ${where} LIMIT 1`
const query = `SELECT ${properties} FROM ${thisObject.TABLE_NAME} WHERE ${where} LIMIT 1`
return await thisDbContext.execute(query)
}

/**
* NOTE: currenlty returns all items as filters have not been implemented yet
* @param {{
* key: string,
* values: []
Expand All @@ -139,8 +139,8 @@ exports.newUserBalanceRepository = function newUserBalanceRepository() {
const properties = propertiesToReturn !== undefined && propertiesToReturn.length > 0
? propertiesToReturn.map(key => structure[key].name).join(',')
: '*'
const where = '' /* needs some consideration */ // `${structure[item.key]} = ${item.value}`
const query = `SELECT ${properties} FROM ${thisObject.TABLE_NAME()} WHERE ${where}`
const where = '' /* needs some consideration */ // 'WHERE ' + items.map( item => `${structure[item.key]} = ${item.value}`).join(' AND ')
const query = `SELECT ${properties} FROM ${thisObject.TABLE_NAME} ${where}`
return await thisDbContext.execute(query)
}

Expand Down
22 changes: 22 additions & 0 deletions Projects/ProjectsSchema.json
Original file line number Diff line number Diff line change
Expand Up @@ -2607,5 +2607,27 @@
]
},
"plugins": []
},
{
"name": "Local-Storage",
"propertyName": "localStorage",
"SA": {
"globals": [
{
"name": "Persistence",
"propertyName": "persistence",
"functionName":"newLocalStorageGlobalsPersistence",
"fileName": "Persistence.js"
}
],
"modules": [
{
"name": "DatabaseRepositories",
"propertyName": "databaseRepositories",
"functionName":"newDatabaseRepositories",
"fileName": "DatabaseRepositories.js"
}
]
}
}
]

0 comments on commit 9ca439b

Please sign in to comment.