Displaying errors in slack modal view - javascript

I'm trying to create a modal which will enable the users to input a date for further use. This date cannot be a date from the past or present (only future dates). Slack indicates that it is possible to validate input data and display errors in the modal views here but I don't really understand this method (I'm a self-learner and a greenhorn).
here's my viewobject in the view.open:
{
type: "modal",
callback_id: "tests",
title: {
type: "plain_text",
text: "Tests",
emoji: true
},
submit: {
type: "plain_text",
text: "Send",
emoji: true
},
close: {
type: "plain_text",
text: "Cancel",
emoji: true
},
blocks: [
{
type: "input",
block_id: "datepicker",
optional: false,
element: {
action_id: "calendar",
type: "datepicker",
initial_date: "2020-09-05",
placeholder: {
type: "plain_text",
text: "Select a date",
emoji: true
}
},
label: {
type: "plain_text",
text: "Label",
emoji: true
}
}
]
}
I need help with displaying the error in the view ( I can already describe that error) after receiving view_submission. Thanks in advance!

First, I highly recommend that, in your code, you change the block_id from "datepicker" to something more descriptive. Slack's example uses "ticket-due-date", so I'll use that.
When a date is entered, Slack will send an HTTP POST request to the endpoint you specified in the Interactivity Request URL. That payload will look something like this (acquired from Block Kit Builder):
{
"type": "block_actions",
"user": {
"id": "U0CA5",
"username": "Amy McGee",
"name": "Amy McGee",
"team_id": "T3MDE"
},
"api_app_id": "A0CA5",
"token": "Shh_its_a_seekrit",
"container": {
"type": "message",
"text": "The contents of the original message where the action originated"
},
"trigger_id": "12466734323.1395872398",
"team": {
"id": "T0CAG",
"domain": "acme-creamery"
},
"response_url": "https://www.postresponsestome.com/T123567/1509734234",
"actions": [
{
"type": "datepicker",
"block_id": "ticket-due-date",
"action_id": "vxw",
"selected_date": "1990-04-26",
"initial_date": "1990-04-28",
"action_ts": "1599429672.233568"
}
]
}
When you receive that request, you need to validate actions[0].selected_date. If invalid, then send the payload below as a POST request to response_url.
{
"response_action": "errors",
"errors": {
"ticket-due-date": "You may not select a due date in the past"
}
}

You need to respond to the same request that is calling your endpoint.
Here's how the interaction endpoint would look like:
app.post("/your_endpoint", (req, res) => {
const validationErrors = {
datepicker: "Please enter a valid date"
};
// Respond to the request with an error payload
res.send({
response_action: "errors",
errors: validationErrors,
});
});

Related

Find specific field in mongoose and validate value of it with express validator

I have a mongoose schema that has an array contains an enum field and value for each enum , I want to for example check that if the enum is nationalId , check the value field of it .
How can I do this with express-validator
Here`s my schema:
fields: {
type: [
{
_id: false,
name: {
type: String,
enum: [
"name",
"nationalId"
],
required: true,
},
value: {
type: String,
default: "",
},
},
],
},
and here is postman json request:
{
"fields": [
{
"name": "nationalId",
"value": "454643"
},
}
here`s my current validation but not work(I use it as middleware and put it before the endpoint in my route) :
exports.isNationalNumber = body("fields.*.name.nationalId")
.exists()
.withMessage({ message: "not valid", errorCode: "1" })
.bail()
.trim()
.matches(/^\d{10}$/)
.withMessage({ message: "not valid", errorCode: "2" })
.bail();
I want to check that if fields name is "nationalId" check the value of it.

Outlook web add in with Graph API - Inline images not displaying when sending current item as an Outlook Item attachment

I am able to send my current item as an attachment , but i am running into a problem where if there are any inline images within my current item, These do not display properly when i open my current item as an attachment from my newly sent/received mail. I understand that the image src is incorrect after sending my original email as an attachment, but im not sure how to rectify this or if this is expected behaviour because i have missed something.
My aim is to forward my current item/email as it appears, as an outlook item to the recipients mailbox.
Im wondering is there an error in how i have set up my json which i post to the Graph API to send mail ? i will post it below incase anything stands out as being set up wrong. Thanks in advance!
var email = client.api('/me/messages/' + restID).get();
var attachments = client.api('/me/messages/' + restID + '/attachments').get()
const sendMail = {
message: {
subject: 'This contains my original email',// forwardMailSubject,
body: {
contentType: "Text",
content: 'Test' // forwardMailBody
},
toRecipients: [
{
emailAddress: {
address: 'test12321#outlook.com' //forwardMailbox
}
}
],
attachments: [
{
'#odata.type': "#microsoft.graph.itemAttachment",
'name': "attachment",
'contentType': "html",
'item': {
"#odata.type": "#microsoft.graph.message",
"id": email.id,
"createdDateTime": email.createdDateTime,
"lastModifiedDateTime": email.lastModifiedDateTime,
"receivedDateTime": email.receivedDateTime,
"sentDateTime": email.sentDateTime,
"hasAttachments": true,
"internetMessageId": email.internetMessageId,
"subject": "Reminder - please bring laptop",
"importance": "normal",
"conversationId": email.conversationId,
"isDeliveryReceiptRequested": false,
"isReadReceiptRequested": false,
"isRead": false,
"isDraft": false,
"webLink": email.webLink,
"body": email.body,
"sender": email.sender,
"from": email.from,
"toRecipients": email.toRecipients,
"attachments": attachments
}
}
]
}
};
client.api('/me/sendMail')
.post(sendMail);

Mongo text index on populated fields

Im just learning indexing with Mongoose/MongoDB and I dont know why this isnt working.
this is my schema
const timeSchema = new mongoose.Schema({
actionId:{
type:String,
required:true
},
start: {
type: Date
},
end: {
type: Date
},
user:{type : mongoose.Schema.Types.ObjectId, ref : 'User'},
task:{type : mongoose.Schema.Types.ObjectId, ref : 'Task'},
pausedSeconds:{
type: Number,
default: 0
}
});
const Time = mongoose.model('Time', timeSchema)
i want to have a text index in two populated fields user and task, i created the index this way
timeSchema.index({"user.name":"text","task.taskName":"text"})
Here is an example of the documents
{
"pausedSeconds": 18,
"_id": "5db1dde8d5bc93526c26fa38",
"actionId": "5feaebcf-6b90-45be-8104-452d643472a0",
"user": {
"_id": "5d4af77e4b6cbf3dd8c5f3ac",
"name": "admin"
},
"task": {
"_id": "5d4aff2f61ad755154b8a1c6",
"taskName": "task 1 updated!"
},
"start": "2019-10-24T17:22:48.000Z",
"end": "2019-10-24T17:30:00.000Z"
},
I have one issue and one question
The issue is:
What im trying to do is get all the documents that have "task 1 updated" (for task.taskName) or
"admin" (for user.name) doing it this way
Time.find({ '$text': { '$search': "admin" } })
Time.find({ '$text': { '$search': "task 1 updated" } })
but it doesnt seem to work
The question is:
If I want to do a text search for the fields start,end being a Date type or for the field pausedSeconds being a Number type what should I do?
Thanks in advance
In your query, you aren't specifying what property to search on. Do this: Time.find({taskName: { '$text': { '$search': "admin" }}}).
Also, I'm not sure if you're just not showing all the code or if you're actually doing your query wrong, but it should be written like this:
Time.find({taskName: { '$text': { '$search': "admin" }}}).exec(function(err, times) {
if(err) return console.log(err);
console.log(times);
});

JSON.parse not returning the orginal object

I am storing a java script object in the DB by converting that into the string by using JSON.stringify, But when i want to retrieve that object from DB i use the JSON.parse. But the JSON.parse is not returning the original object. In the below console screenshot it can be seen that the object Obj had some changes after it is converted into string and then parsed. So how can i get back the original object after doing JSON.stringify
The Object is as below:
var Obj = {
onchange: function(){
},
validate: function(obj){
},
elements: {
"list": {
menu: [{
caption: "Append an",
action: Xonomy.newElementChild,
actionParameter: "dd"
}]
},
"item": {
menu: [{
caption: "Add ",
action: Xonomy.newAttribute,
actionParameter: {name: "label", value: "something"},
hideIf: function(jsElement){
return jsElement.hasAttribute("label");
}
}, {
caption: "Delete this ",
action: Xonomy.deleteElement
}, {
caption: "New before this",
action: Xonomy.newElementBefore,
actionParameter: "sas"
}, {
caption: "New after this",
action: Xonomy.newElementAfter,
actionParameter: "aa"
}],
canDropTo: ["list"],
attributes: {
"label": {
asker: Xonomy.askString,
menu: [{
caption: "Delete this",
action: Xonomy.deleteAttribute
}]
}
}
}
}
};
As already mentioned in comments - you can't serialize JS functions with JSON.stringify. Please take a look at serialize-javascript library to store the functions.

Unexpected error in parsing json

Using the tutorial given here, I am making an app to fetch json data from a URL and display it. I am using this code to call the URL and parse.
{
xtype: 'nestedlist',
title: 'Blog',
iconCls: 'star',
cls: 'blog',
displayField: 'title',
store: {
type: 'tree',
fields: ['uuid', 'display'
],
root: {
leaf: false
},
proxy: {
type: 'scripttag',
url: 'http://localhost:8081/openmrs-standalone/ws/rest/v1/location',
reader: {
type: 'json',
rootProperty: 'results'
}
},
},
},
In the console i am getting response in the form
{
"results": [
{
"uuid": "c0937f0c-1691-11df-97a5-7038c432aabf",
"display": "Chulaimbo",
"links": [
{
"uri": "http://localhost:8081/openmrs-standalone/ws/rest/v1/location/c0937f0c-1691-11df-97a5-7038c432aabf",
"rel": "self"
}
]
},
{
"uuid": "c0937d4f-1691-11df-97a5-7038c432aabf",
"display": "Mosoriot Hospital",
"links": [
{
"uri": "http://localhost:8081/openmrs-standalone/ws/rest/v1/location/c0937d4f-1691-11df-97a5-7038c432aabf",
"rel": "self"
}
]
},
{
"uuid": "8d6c993e-c2cc-11de-8d13-0010c6dffd0f",
"display": "Unknown Location",
"links": [
{
"uri": "http://localhost:8081/openmrs-standalone/ws/rest/v1/location/8d6c993e-c2cc-11de-8d13-0010c6dffd0f",
"rel": "self"
}
]
}
]
}
but its showing an error
"location" is the name of the service.
The console believes you are trying to execute the JSON as code. So after the first {, it expects instruction. Not data. Try putting parentheses around the entire thing:
{ myfield: 1, anotherfield: 2 } (ERROR)
({ myfield: 1, anotherfield: 2 }) (SUCCESS)
This will resolve the issue.
I have done it using a different method. I used proxytype 'rest' and run OpenMRS and my application on the same server and port otherwse my instance of OpenMRS wont allow cross-domain calls. The problem in this question was using type as "scripttag" which i still dont know what is the problem with it.Using "rest" resolves it.

Categories

Resources