I'm working on a project where i want to schedule notifications every X days.
here is the part where i schedule notifications :
let notificationId = await Notifications.scheduleNotificationAsync({
content: {
title: title,
body: body,
data: null,
},
trigger: { day: freq, repeats: true },
});
I tried with
trigger: { hour: freq * 24, repeats: true },
But every time i get this error :
[Unhandled promise rejection: Error: Failed to schedule the notification. Trigger of type: calendar is not supported on Android.]
I know some people will maybe say it's because i try it on emulator but it should still work and to be sure i try on my phone too and it still doesn't work.
Try this
const trigger = await Notifications.getNextTriggerDateAsync({
channelId: DECKS_NOTIFICATION_CHANNEL_ID,
hour: 20,
minute: 0,
repeats: true,
//seconds: 2,
})
then
let notificationId = await Notifications.scheduleNotificationAsync({
content: {
title: title,
body: body,
data: null,
},
trigger
});
There are so many types of SchedulabeNotificationTriggers. The one i showed you is for daily. You can check more in this link
Expo Notifications
Related
I am relatively new to Next.js, and I though I have been encountering some bugs and issues here and there, I have been able to overcome most of them. The latest one I have not been able to figure out, so let's see if somebody else knows what's going on.
I am creating an e-commerce platform on Next.js, Redux and Axios. For the moment I am using fake data to populate the products. When creating a checkout session, the data of the items in the cart is pushed (I can console.log() and I see the items in the terminal. However, the mapping of the checkout session to Stripe is not working. The error I get is an AxiosError: Request failed with status code 500
Error message screenshot
I am trying to add the item data dynamically to the checkout session as follows:
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
export default async (req, res) => {
const { items, email } = req.body;
const transformedItems = items.map((item) => ({
description: item.description,
// if quantities are bundled, this needs to change.
quantity: 1,
price_data: {
currency: 'usd',
unit_amount: item.price * 100,
product_data: {
name: item.title,
images: [item.image],
},
},
}));
const session = await stripe.checkout.sessions.create({
line_items: transformedItems,
mode: 'payment',
success_url: `${process.env.HOST}/success`,
cancel_url: `${process.env.HOST}/checkout`,
metadata: {
email,
images: JSON.stringify(items.map((item) => item.image)),
},
});
res.status(200).json({ id: session.id });
};
I have also tried copying the exact code from the Stripe documentation and implementing the changes, but this hasn't changed anything either.
I know, Stripe has made some changes to their API, and that for instance you can't specify anymore with statements like
payment_method_types: ["card"],
anymore. So I took it out.
I have not included any code from the checkout piece, as this seems to be working (as stated, it console.logs() just fine. I can provide this as well though, if someone thinks the issue might be there.
Thanks in advance.
Nela.
Thanks to Code-Apprentice and maiorano84 whose hints in the comments:
A status code 500 means there is an error on the backend. If the server is under your control, then you need to look at the server logs to see what the problem is. The server logs will have a stack trace that shows you where the problem occurs. If you need help understanding the stacktrace, you will need to include it in your question. – Code-Apprentice 22 hours ago
Is this a server-side or client-side AJAX request? If it's the latter, check your network tab to see the full output of your failed request (marked in red in Chrome Devtools). You should be able to get more information about the failed request there. If it's failing on the Stripe side, the Response Headers and Body should have more information there to help you debug. If it's failing on your own success and checkout callbacks, your server logs might have additional information that can help you. – maiorano84 22 hours ago
led me to the answer. I checked my console, and the error that was given was from Stripe. It read as follows:
StripeInvalidRequestError: You cannot use line_items.amount, line_items.currency, line_items.name, line_items.description, or line_items.images in this API version. Please use line_items.price or line_items.price_data.
So I moved the item.description I had outside of the product_data object, into it, and it worked.
The code looks now like this:
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
export default async (req, res) => {
const { items, email } = req.body;
const transformedItems = items.map((item) => ({
// if quantities are bundled, this needs to change.
quantity: 1,
price_data: {
currency: 'usd',
unit_amount: item.price * 100,
product_data: {
name: item.title,
description: item.description,
images: [item.image],
},
},
}));
const session = await stripe.checkout.sessions.create({
line_items: transformedItems,
mode: 'payment',
success_url: `${process.env.HOST}/success`,
cancel_url: `${process.env.HOST}/checkout`,
metadata: {
email,
images: JSON.stringify(items.map((item) => item.image)),
},
});
res.status(200).json({ id: session.id });
};
I'm a student working on a chat application for my internship, where I use socket.io.
Right now I am busy thinking of a good way to store the messages send in conversations.
As of now I do the following:
For each conversation between one user and another user, a new collection is made.
On every message sent, the message is stored in the according conversation collection in a single document.
The collections:
Where the document looks as follows:
Now I wonder if there is a good argument to be made to have just one collection "conversations", and store all the messages in multiple documents, where each conversation is a new document.
Creating a new collection for every message is very bad idea instead of that you use a simple schema as given below to store your messages
const conversation_schema = new Schema({
from: {
type: ObjectID,
ref: 'User'
},
to: {
type: ObjectID,
ref: 'User'
},
messageBody: { // body of the message(text body/ image blob/ video blob)
type: String,
},
messageType: { // type of the message(text, mp3, mp4, etc...)
type: String,
},
read: { // to boolean flag to mark whether the to user has read the message
type: Boolean,
default: false,
},
createdAt: { // when was this message goit created
type: Date,
default: new Date(),
},
});
you can fetch the conversation between the two users using the following query
conversations.find({
$or: [
{from: 'user1', TO: 'user2},
{from: 'user2', TO: 'user1},
],
}).populate({ path: 'to', model: User })
.populate({ path: 'from', model: User })
.sort({ createdAt: -1 })
I am getting a SequelizeDatabaseError Data truncated for column 'position' at row 4 while sending an update request as below: Any advise on how to fix the database error ?
Executing (default): UPDATE user SET photo=?,name=?,email=?,phonenumber=?,position=?,password=?,updatedAt=? WHERE email = ?
SequelizeDatabaseError: Data truncated for column 'position' at row 4
at Query.formatError (C:\Project\soccerpep\node_modules\sequelize\lib\dialects\mysql\query.js:244:16)
at Execute.handler [as onResult] (C:\Project\soccerpep\node_modules\sequelize\lib\dialects\mysql\query.js:51:23)
module.exports = function(sequelize, DataTypes) {
return sequelize.define('user', {
name: {
type: DataTypes.STRING(30),
allowNull: false
},
email: {
type: DataTypes.STRING(100),
allowNull: false
},
phonenumber: {
type: DataTypes.STRING(50),
},
id: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
password: {
type: DataTypes.STRING(50),
allowNull: false
},
privilege: {
type: DataTypes.ENUM('PLAYER','ADMIN'),
},
photo: {
type: DataTypes.STRING(30),
},
position: {
type: DataTypes.ENUM('FORWARD','MID-FIELD','DEFENDER','GK'),
}
}, {
tableName: 'user'
});
};
server.js
const UserModel = userSchema(sequelize, DataTypes);
app.put('/service/profile', async (req, res, next) => {
try {
const userEmail = req.query.email;
var selector = {
where: { email: userEmail }
};
const updatePlayer = await UserModel.update(req.body, selector);
console.log("Server side update method log:" + updatePlayer);
res.status(200).json({ success: true });
} catch (err) {
return next(err);
}
});
I think the issue is with ENUM, you can use that only with Postgres and not with mysql , ( Ref )
position: {
type: DataTypes.ENUM('FORWARD','MID-FIELD','DEFENDER','GK'),
}
Change it to simple string type and check again,
position: {
type: DataTypes.STRING(30)
}
NOTE : You might need to create table again or update the field
manually after changing this in model else you will still get the
error
If you want to use ENUMs in mysql you should use it as so
position: {
type: DataTypes.ENUM,
values: ['player', 'admin],
defaultValue: 'monthly' // A default value just incase you fail to provide one...
},
I do hope this helps...
Change datatype is not the solution. You have to check the data that you try to save. eg: if ENUM("0", "1") and you try to saved data 0 then it's showing that type of error. You have to save like that "0". Then it's not showing such type of error message again.
i have a lot spending my day to tracing this error.
i have following all solution but doesnt work.
in my case and my bad is...
i forgot have clone table/duplicate/history/trigger that save old and new data.
make sure your history table have same data type.
i have table like these
form3
hs_form3 // its mean history with revision (number of revisi data) column and action column (create/update/delete/any)
just for description
CREATE TABLE hs_form3 LIKE form3;
ALTER TABLE hs_form3 MODIFY COLUMN id int(11) NOT NULL,
DROP PRIMARY KEY, ENGINE = InnoDB, ADD action VARCHAR(8) DEFAULT 'insert' FIRST,
ADD revision INT(6) NOT NULL AUTO_INCREMENT AFTER action,
ADD dt_datetime DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER revision,
ADD PRIMARY KEY (revision),
ADD KEY `user_id` (`user_id`),
and i didnt run migration on server because a lot of change , i only run on localhost. in server i just put a new table by export import or added manual. before i got issue about migration on server and doesnt capture last change in sql table and dont have time to resolve.
I'm trying to POST a record to my MS SQL database and I'm getting an Internal Server Error status of 500 which is the response programmed in the api:
exports.create = (req, res) => {
// Save Budget to MSSQL database
Budgets.create({
clientid: req.body.clientid,
catitem: req.body.catitem,
subcatitem: req.body.subcatitem,
startDate: req.body.startDate,
endDate: req.body.endDate,
quantity: req.body.quantity,
frequency: req.body.frequency,
cost: req.body.cost
}).then(budget => {
// Send created budget to budget
res.send(budget);
}).catch(err => {
res.status(500).send("Error -> " + err);
})
};
Here is the code for posting the record from the client:
export const createBudget = (budgetData = {
clientid: null,
catitem: '',
subcatitem: '',
startDate: '',
endDate: '',
quantity: '',
frquency: '',
cost: ''
}) => {
return (dispatch) => {
const budget = {
clientid: budgetData.clientid,
catitem: budgetData.catitem,
subcatitem: budgetData.subcatitem,
startDate: budgetData.startDate,
endDate: budgetData.endDate,
quantity: budgetData.quantity,
frequency: budgetData.frequency,
cost: budgetData.cost
};
return axios.post('budgets/create', budget).then(result => {
dispatch(_createBudget(result.data));
});
};
};
Initially this worked with with just four columns in the table (clientid, catitem, subcatitem, and cost) but I had to add extra columns and now it dosen't work. When I click the link shown in Developer Tools I get a page that states: "Cannot GET /api/budgets/create" yet the route defined in the api is: "app.post('/api/budgets/create', budgets.create);"
Is the "Cannot GET /api/budgets/create" the typical response for a failure to a post or is there something else going on? And how do I determine what the root cause is for the failure? Also I can INSERT a record into the table using Azure Data Studio with a SQL statement (developing on a Mac).
So after further analysis I discovered that I had to manually add the fields createdAt and updatedAt (required by Axios) to the database table then restart the Docker MS Sql service. Everything now works. What tipped me off to this solution was noticing and examining the initial get of the Budgets table and that's what was failing and therefor the failing of the POST request.
Update: I've gotten a fair bit further. Please see the bottom of the post...
I'm working on a project that is based on the sql-fullstack yeoman generator, and have been using the included example code as a guide. Things have progressed smoothly, for the most part, but I'm now in a scenario where I have two tables/models with a bidirectional n:m relationship:
TaskGroup:
module.exports = function(sequelize, DataTypes) {
var TaskGroup = sequelize.define("TaskGroup", {
taskGroupID: {
field: "TaskGroupID",
type: DataTypes.INTEGER,
allowNull: false,
unique: true,
autoIncrement: true,
primaryKey: true
},
name: {
field: "Name",
type: DataTypes.STRING,
allowNull: false
},
description: {
field: "Description",
type: DataTypes.STRING
},
modifiedBy: {
field: "ModifiedBy",
type: DataTypes.STRING
}
});
and Task:
module.exports = function(sequelize, DataTypes) {
var Task = sequelize.define("Task", {
taskID: {
field: "TaskID",
type: DataTypes.INTEGER,
allowNull: false,
unique: true,
autoIncrement: true,
primaryKey: true
},
name: {
field: "Name",
type: DataTypes.STRING,
allowNull: false
},
description: {
field: "Description",
type: DataTypes.STRING
},
isOnRunsheet: {
field: "IsOnRunsheet",
type: DataTypes.BOOLEAN
},
modifiedBy: {
field: "ModifiedBy",
type: DataTypes.STRING
}
});
Relationships:
// Tasks can belong to more than one group, and groups can belong to more than one task
db['TaskGroup'].belongsToMany(db['Task'], {as: 'Tasks', through: 'TaskGrouping'});
db['Task'].belongsToMany(db['TaskGroup'], {as: 'TaskGroups', through: 'TaskGrouping'});
On the client side, the user is able to create a new task and specify the associated task groups through a multiple select list. When the task is saved, I have both the task fields and an array of the associated task groups. A post is made with the request body containing this information, so that the server can create the task record.
Unfortunately, I can't seem to get the record created. I've been through a number of iterations, and I'm at the point where I get what appears to be a reasonable exception - I'm just stumped as to what the "reasonable" thing to do is...
Exception:
Unhandled rejection SequelizeDatabaseError: Cannot insert the value NULL into column 'TaskTaskID', table 'HelpCard
.dbo.TaskGrouping'; column does not allow nulls. INSERT fails.
at Query.formatError (C:\Projects\helpcard2\node_modules\sequelize\lib\dialects\mssql\query.js:215:10)
at Request.userCallback (C:\Projects\helpcard2\node_modules\sequelize\lib\dialects\mssql\query.js:66:25)
at Request.callback (C:\Projects\node_modules\tedious\lib\request.js:33:27)
at Connection.message (C:\Projects\node_modules\tedious\lib\connection.js:1179:27)
at Connection.dispatchEvent (C:\Projects\node_modules\tedious\lib\connection.js:519:45)
at MessageIO.<anonymous> (C:\Projects\node_modules\tedious\lib\connection.js:439:23)
at emitNone (events.js:67:13)
at MessageIO.emit (events.js:166:7)
at ReadablePacketStream.<anonymous> (C:\Projects\node_modules\tedious\lib\message-io.js:92:15)
at emitOne (events.js:77:13)
...
Here's the code on the client side:
$scope.createTask = function() {
if($scope.newTask === '') {
return;
}
$scope.newTask.modifiedBy = 'tkturney';
var taskBundle = {
task: $scope.newTask,
taskGroups: $scope.selectedGroups
};
$http.post('/api/tasks', taskBundle);
setTimeout(function() {
$scope.currentTask = $scope.newTask;
$scope.newTask = '';
$scope.addingTask = false;
refreshTasks();
}, 250);
};
...and on the server side:
exports.create = function(req, res) {
var task = Task(req).build(req.body.task);
task.setTaskGroups(req.body.taskGroups);
task
.save()
.then(function() {
return res.status(201).json(task);
})
.catch(function (err){
if(err) { return handleError(res, err); }
});
};
I'm sure that I'm missing something obvious, but the documentation that I've found has been pretty light on a scenario like this. I would appreciate any guidance; I'm just getting into sequelize, and I feel that there are times that I may have bitten off more than I can chew... :)
Update: After taking a closer look at the SQL, I discovered that the exception was being thrown when trying to insert into the join table (TaskGroupings). It was trying to insert a NULL for the task's primary ID, which is generally not a good thing. Looking at the code, I realized that I was trying to add the association before I had saved the record, leaving me with no PK. Moving the task.addTaskGroups() after the save() took care of that issue.
However, I also realized that I was passing an array of TaskGroup objects to the 'addTaskGroup()` call, instead of the actual IDs. So, I modified the client-side controller like so:
$scope.createTask = function() {
if($scope.newTask === '') {
return;
}
$scope.groupKeys = [];
angular.forEach($scope.selectedGroups, function(taskGroup) {
$scope.groupKeys.push(taskGroup.taskGroupID);
});
$scope.newTask.modifiedBy = 'tkturney';
var taskBundle = {
task: $scope.newTask,
taskGroups: $scope.groupKeys
};
$http.post('/api/tasks', taskBundle);
...
When I look at the debugger, I can see everything in the taskGroup object, but taskGroup.taskGroupID is coming back as undefined, so I'm still getting an exception because I'm not passing the PKs for the other side of the association.
Does anything leap out as to what might be screwy with this code fragment?
Ok, by changing the server-side controller from this:
exports.create = function(req, res) {
var task = Task(req).build(req.body.task);
task.setTaskGroups(req.body.taskGroups);
task
.save()
.then(function() {
return res.status(201).json(task);
})
.catch(function (err){
if(err) { return handleError(res, err); }
});
};
To this:
exports.create = function(req, res) {
var task = Task(req).build(req.body.task);
task
.save()
.then(function() {
task.setTaskGroups(req.body.taskGroups);
return res.status(201).json(task);
})
.catch(function (err){
if(err) { return handleError(res, err); }
});
};
That particular exception went away. The thing that I was missing (though it was staring me in the face) was the fact that there are two separate inserts happening - one for the task, and one for the association. I was thinking that I needed to set the association before saving the task, not realizing that setting that association caused another insert.
I still need to figure out why the PKs for the other side of the association aren't getting populated, but that's outside the scope of the original question...