Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
public async read(
tableName: string,
primaryKey: PrimaryKey,
): Promise {
const file = this.resolvePath(tableName, primaryKey);
let data: any;
try {
data = await fs.readFile(file, {encoding: 'utf8', flag: 'r'});
} catch (error) {
if (error.code === 'ENOENT') {
const message = `Record "${primaryKey}" in "${tableName}" could not be found.`;
throw new StoreEngineError.RecordNotFoundError(message);
}
throw error;
}
try {
data = JSON.parse(data);
} catch (error) {
// No JSON found but that's okay
}
return data;
}
public async read(
tableName: string,
primaryKey: PrimaryKey,
): Promise {
const key = `${this.storeName}@${tableName}@${primaryKey}`;
const record = this.webStorage.getItem(key);
if (record) {
try {
const parsed = JSON.parse(record);
return parsed;
} catch (error) {
return record as any;
}
}
const message = `Record "${primaryKey}" in "${tableName}" could not be found.`;
throw new StoreEngineError.RecordNotFoundError(message);
}
const table = this.schema[tableName];
if (!table) {
throw new Error(`Table "${tableName}" does not exist.`);
}
const columns = getFormattedColumnsFromTableName(table);
const escapedTableName = escape(tableName);
const selectRecordStatement = `SELECT ${columns} FROM ${escapedTableName} WHERE ${SQLeetEnginePrimaryKeyName}=@primaryKey;`;
const statement = await this.db.prepare(selectRecordStatement, {
'@primaryKey': primaryKey,
});
const record = (await statement.getAsObject())[0];
await statement.free();
if (typeof record === 'undefined') {
const message = `Record "${primaryKey}" in "${tableName}" could not be found.`;
throw new StoreEngineError.RecordNotFoundError(message);
}
for (const column in record) {
if (table[column] === SQLiteType.JSON) {
record[column] = JSON.parse(record[column]);
} else if (table[column] === SQLiteType.JSON_OR_TEXT) {
try {
record[column] = JSON.parse(record[column]);
} catch (error) {}
}
}
if (isSingleColumnTable(table)) {
return record[RESERVED_COLUMN];
}
public async update(
tableName: string,
primaryKey: PrimaryKey,
changes: Object,
): Promise {
const updatedRecords = await this.db.table(tableName).update(primaryKey, changes);
if (updatedRecords === 0) {
const message = `Record "${primaryKey}" in "${tableName}" could not be found.`;
throw new StoreEngineError.RecordNotFoundError(message);
}
return primaryKey;
}
async read(tableName: string, primaryKey: PrimaryKey): Promise {
const filePath = this.createFilePath(tableName, primaryKey);
let data: string;
try {
data = await fs.readFile(filePath, {type: 'Text'});
} catch (error) {
const message = `Record "${primaryKey}" in "${tableName}" could not be found.`;
throw new StoreEngineError.RecordNotFoundError(message);
}
try {
const parsed = JSON.parse(data);
return parsed;
} catch (error) {
return data as any;
}
}