Created
December 29, 2022 03:33
-
-
Save Juandresyn/b7715010b9d0c51d8fc95da7dd22e3a0 to your computer and use it in GitHub Desktop.
BD local orm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Sql { | |
repository; | |
constructor() { | |
this.repository = []; | |
} | |
createTable(tableName, values) { | |
this.repository.push({ | |
[tableName]: { | |
format: [values], | |
rows: [] | |
} | |
}); | |
return this.repository; | |
} | |
getTable(tableName) { | |
const getFreshCopy = () => this.repository.filter(t => { | |
return Object.keys(t)[0] === tableName | |
}); | |
const table = getFreshCopy(); | |
if (table.length < 1) return []; | |
return { | |
insertRecord: (item) => { | |
const Table = table[0][tableName]; | |
if (this.checkFormat(Table.format, item)) { | |
Table.rows.push(item); | |
return table; | |
} | |
console.log(`ERROR: Could not insert object: ${ JSON.stringify(item) } in table ${ tableName }. Check object types`) | |
}, | |
getRecords: (args) => { | |
const db = getFreshCopy()[0][tableName].rows; | |
const checkProp = (row, prop) => args[prop] ? row[prop] === args[prop] : true | |
return db.filter(r => checkProp(r, 'name') && checkProp(r, 'quantity')) || [] | |
}, | |
getAllRecords: () => { | |
return getFreshCopy()[0][tableName].rows; | |
} | |
} | |
} | |
checkFormat(format, values) { | |
if (format.length < 1 || values.length < 1) return; | |
return Object.keys(values).every(key => typeof values[key] === format[0][key]); | |
} | |
} | |
const SQL = new Sql(); | |
SQL.createTable('fruit', { name: 'string', quantity: 'number' }); | |
const table = SQL.getTable('fruit'); | |
table.insertRecord({ name: 'Apple', quantity: 20 }); | |
table.insertRecord({ name: 'Orange', quantity: 20 }); | |
table.insertRecord({ name: 'Pineapple', quantity: '20' }); | |
table.insertRecord({ name: 'Grape', quantity: 12 }); | |
console.log('get apples:', table.getRecords({ name: 'Apple', quantity: 20 })); | |
console.log('get quantity 20:', table.getRecords({ quantity: 20 })); | |
console.log('get quantity 12:', table.getRecords({ quantity: 12 })); | |
console.log('get oranges:', table.getRecords({ name: 'Orange' })); | |
console.log('get bananas:', table.getRecords({ name: 'Bananas' })); | |
console.log('all records:', table.getAllRecords()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment