Node Express - Database is created too late causing error - node-sqlite3

My problem is with creating a database. It is created too late and causes problems with further queries. I tried to use async and await but it seems it doesn't solve the problem.
async function storeDailyDealToDB(dailyDeal) {
const db = new sqlite3.Database('database.db');
await new Promise((resolve) => {
const QUERY_CREATE_TABLE =
"CREATE TABLE IF NOT EXISTS daily_deal ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT,)";
db.run(QUERY_CREATE_TABLE);
resolve("done")
});
await new Promise((resolve) => {
const insert =
"INSERT INTO daily_deal (title) VALUES (?)";
const stmt = db.prepare(insert);
stmt.run([dailyDeal['title']]);
stmt.finalize();
resolve("done")
});
let lastRow = await new Promise((resolve) => {
db.each("SELECT * FROM daily_deal ORDER BY id DESC LIMIT 1", function (err, row) {
resolve(err == null ? {} : row)
});
});
db.close();
return lastRow
}
Here is the error I get:
[Error: SQLITE_ERROR: no such table: daily_deal
Emitted 'error' event on Statement instance at:
] {
errno: 1,
code: 'SQLITE_ERROR'
}
Node.js v17.9.0
I did a lot of research and I am stuck. I read to use Promise but it works partially. I am not sure how to tackle this problem.

After looking at the reference docs, of Database#run, you should pass a callback to the run method. Inside this callback, you want to either resolve or reject the promise depending on the outcome.
await Promise((res, rej) => {
db.run(..., (err, result) => {
if (err) rej(err) else res(result)
});
});
I think this is correct (untested however).

Related

ParseServer object not found

Parse.Query in cloud code cant find object
Running this code cloud function as a user who can reject or accept Invites. The code gets the invite (works) and checks for the given deckId, where the user should be added as a collaborator.
But for some reason i can't explain the Query for the Deck always returns:
https://pastebin.com/XjLjvzXZ
I have checked:
the docs for syntax -> should be fine
the Invite object exists and has a deckId
The Deck Objects exist and the deckId and Deck's objectId are matching
Parse.Cloud.define("inviteAction", async (request) =>
{
const user = request.user;
const inviteId = request.params.invite;
const action = request.params.actiom;
let inviteQuery = new Parse.Query("Invite");
const invite = await inviteQuery.get(inviteId, { useMasterKey: true } );
if (invite != null && invite != undefined)
{
const deckId = invite.get("deckId");
console.log(deckId);
if (invite.get("invited") === user.getUsername())
{
if (action === "accept")
{
let deckQuery = new Parse.Query("Deck");
await deckQuery.get(deckId, { useMasterKey: true } ).then((deck) =>
{
console.log(deck);
deck.addUnique("collaborators", user.getUsername());
deck.save();
}).catch((error) =>
{
console.log(error); // is always error
});
}
invite.destroy();
return true;
}
}
return false;
});
This gives me the same error:
let deckQuery = new Parse.Query("Deck");
await deckQuery.find({ useMasterKey: true } ).then((deck) =>
{
console.log(deck.length);
}).catch((error) =>
{
console.log(error);
});
OMG im so dumb,
apparently you get this error if you have a typo as well.
I just changed
const action = request.params.actiom;
to
const action = request.params.action;

How do I use createAsyncThunk to repeatedly fetch data automatically?

The goal is to repeatedly fetch generation data when the Id changes...The generation Id changes at the backend
Only AFTER I used redux tool kit and createAsyncThunk, did it stop refreshing generation Id automatically, unless I manually refresh the page (will it show the latest generationId)
The change I've made, so how should I do it? Thanks.
in generationSlice.js
export const getGeneration = createAsyncThunk(
'generation/getGeneration',
async () => {
try {
const resp = await axios(url)
return resp.data
} catch (error) {
return error.response
}
}
)
and
in components/Generation.js
const { generationId, expiration, isLoading } = useSelector((store) => {
return store.generation
})
const dispatch = useDispatch()
useEffect(() => {
dispatch(getGeneration())
}, [generationId])

Issue while updating store from updater function of commitMutation

I have a mutation
mutation createQuoteLineMutation {
createQuoteLine {
quoteLine {
name
price
product {
name
}
}
}
}
My updater function is as below.
updater: (store) => {
const payload = store.getRootField('createQuoteLine');
const newQuoteLine = payload.getLinkedRecord('quoteLine');
const quote = store.getRoot().getLinkedRecord('getQuote');
const quoteLines = quote.getLinkedRecords('quoteLines') || [];
const newQuoteLines = [...quoteLines, newQuoteLine];
quote.setLinkedRecords(newQuoteLines, 'quoteLines');
}
This works fine for the first time, but the consequent mutations all the previously added quoteLines change to new one I'm assuming this is because newQuoteLine points to same object all the time.
adding below line at the end of updater function unlink quoteLine from createQuoteLine also does not work.
payload.setValue(null, 'quoteLine');
Any help in this regard is highly appreciated.
I have seen a quite similar problem, but I am not sure if it's the same. Try to pass an clientMutationId to the mutation, and increment it along.
const commit = (
input,
onCompleted: (response) => void,
) => {
const variables = {
input: {
...input,
clientMutationId: temp++,
},
};
commitMutation(Environment, {
mutation,
variables,
onCompleted,
onError: null,
updater: store => {
// ....
},
});
};
Try something like this and let me know if it fixes :).

Can't update index dynamically with dexie sample code

I have been trying updating the db index dynamically and keeps failed, stuck for a few days.
I'm using angular7 & type script and latest dexie version. When I try to use the same code, it give me error:
Is there anything I should do to get it working? Thx!
ERROR Error: Uncaught (in promise): UpgradeError: Dexie specification of currently installed DB version is missing
UpgradeError: Dexie specification of currently installed DB version is missing
I literally just copy pasted the sample code here:
changeSchema(db, schemaChanges) {
db.close();
const newDb = new Dexie(db.name);
newDb.version(db.verno + 1).stores(schemaChanges);
return newDb.open();
}
// Open database dynamically:
async playAround() {
let db = new Dexie('FriendsDatabase');
if (!(await Dexie.exists(db.name))) {
db.version(1).stores({});
}
await db.open();
// Add a table with some indexes:
db = await this.changeSchema(db, { friends: 'id, name' });
// Add another index in the friends table
db = await this.changeSchema(db, { friends: 'id, name, age' });
// Remove the age index again:
db = await this.changeSchema(db, { friends: 'id, name' });
// Remove the friends table
db = await this.changeSchema(db, { friends: null });
}
This sample was faulty. I've updated the docs with a working sample:
async function changeSchema(db, schemaChanges) {
db.close();
const newDb = new Dexie(db.name);
newDb.on('blocked', ()=>false); // Silence console warning of blocked event.
// Workaround: If DB is empty from tables, it needs to be recreated
if (db.tables.length === 0) {
await db.delete();
newDb.version(1).stores(schemaChanges);
return await newDb.open();
}
// Extract current schema in dexie format:
const currentSchema = db.tables.reduce((result,{name, schema}) => {
result[name] = [
schema.primKey.src,
...schema.indexes.map(idx => idx.src)
].join(',');
return result;
}, {});
console.log("Version: " + db.verno);
console.log("Current Schema: ", currentSchema);
// Tell Dexie about current schema:
newDb.version(db.verno).stores(currentSchema);
// Tell Dexie about next schema:
newDb.version(db.verno + 1).stores(schemaChanges);
// Upgrade it:
return await newDb.open();
}
// Open database dynamically:
async function playAround() {
let db = new Dexie ('FriendsDatabase2');
if (!(await Dexie.exists(db.name))) {
console.log("Db does not exist");
db.version(1).stores({});
}
await db.open();
console.log("Could open DB")
// Add a table with some indexes:
db = await changeSchema(db, {friends: 'id, name'});
console.log("Could enforce friends table with id and name")
// Add another index in the friends table
db = await changeSchema(db, {friends: 'id, name, age'});
console.log("Could add the age index")
// Remove the age index again:
db = await changeSchema(db, {friends: 'id, name'})
console.log("Could remove age index")
// Remove the friends table
db = await changeSchema(db, {friends: null});
console.log("Could delete friends table")
}
playAround().catch(err => console.error(err));
Fiddle:
https://jsfiddle.net/dfahlander/jzf2mc7n/

Primary sort key DynamoDB attribute expression

I am new to DynamoDB and want only to create a new object if the Primary sort key(name) does not exist twice. I tried it like this:
params.id = randomId();
var item = {
TableName: tableName,
Item: params,
ConditionExpression: "#na <> :n",
ExpressionAttributeNames:{"#na":"name"},
ExpressionAttributeValues:{
":n":params.name
}
};
docClient.put(item, function(err, data) {
console.log("Data:", data);
console.log("Err:", err);
});
But the item is still created :/ Is ist even possible to create a condition expression on the primary sort key ?
Actually just ran into this issue myself, as explained here it looks like you can't, you'll have to use a Global Secondary Index for the 'sort' key.
You will have to do a seperate get request on the GSI first to see if "name" exists for eg.
function checkNameDoesNotExist(name, fn){
query.IndexName = 'nameInUsers';
query.KeyConditionExpression = 'name = :n';
query.ExpressionAttributeValues = {
':n': name
};
dynamodb.query(query, function(err, data){
if (err) {
return fn(err);
} else {
fn(null, data);
}
});
}
Disclaimer: wrote the code off the top of my head, don't know if it works but should give you a good starting point
You can use the exist condition. It will return an error saying that the object already exists
var item = {
TableName: tableName,
Item: params,
Expected: {
name: {
Exists: false
}
};
docClient.put(item, function(err, data) {
console.log("Data:", data);
console.log("Err:", err);
});

Resources