Zod refine arguments provide the unvalidated raw data - zod

const dateValidator = z
.string({ required_error: 'expected YYYY-MM-DD', invalid_type_error: 'expected YYYY-MM-DD' })
.regex(/^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$/, { message: 'must be in YYYY-MM-DD format' })
.transform((v) => new Date(v + 'T00:00:00.000Z'))
const validateStartEndDates = (searchParams: URLSearchParams) =>
z
.object({ start: dateValidator, end: dateValidator })
.refine(({ start, end }) => { // start, end return raw string
return end.getTime() >= start.getTime()
}, 'end date must be larger or equal to start date')
.parse({ start: searchParams.get('start'), end: searchParams.get('end') })
If I hover my mouse on start, end on refine args, they show up as the transformed Date type correctly, but if I console.log out those values from refine args, they are raw string format, this ends up end.getTime() throwing an error.

Related

How to use for loop to create multiple dates?

I have a function here that gets the date, and adds one week to it:
func thingy() {
let currentDate = Date()
var dateComponent = DateComponents()
dateComponent.day = 7
let futureDate = Calendar.current.date(byAdding: (dateComponent*i), to: currentDate)
print(futureDate!.formatted())
}
This gets the current date, adds one week to it, and prints out that date.
I want to get a for loop that will give the date, for example maybe 10 weeks in the future, maybe looking something like this:
for i in 1...num[ex: 11] {
let currentDate = Date()
var dateComponent = DateComponents()
dateComponent.day = 7
let futureDate = Calendar.current.date(byAdding: (dateComponent*i), to: currentDate)
let match = (title: "Test", date: futureDate)
}
I get this error:
Referencing operator function '*' on 'DurationProtocol' requires that 'DateComponents' conform to 'DurationProtocol'
How do I fix this?
I would advise adding .weekOfYear to the date. E.g., to get an array of Date representing the next ten weeks:
let calendar = Calendar.current
let today = calendar.startOfDay(for: Date())
let dates = (1 ... 10)
.compactMap { calendar.date(byAdding: .weekOfYear, value: $0, to: today) }

firebase realtime DB: TypeError: Cannot convert undefined or null to object

I am having query like below
var db = admin.database();
var ref = db.ref('orders') ref.orderByChild("order/_date").startAt(begDate).endAt(endDate).once("value").then(
(resp) => {
..
}).catch(
(err) => console.log('failed in sales report:' + err)
)
it throws below
TypeError: Cannot convert undefined or null to object
The data looks like below
orders: {
"-LNMPXMb1SGSnkDaEMQO" : {
"order" : {
"_cgst" : "11.90",
"_date" : "1538368446413",
"_location" : "kapashera",
"_orderNumber" : "VikKumar-21247",
"_orderStatus" : "Delivered",
}
},
At the time of execution the begDate and endDate are:
begDate:1538352000000 endDate:1538438400000
So two problems:
1.The error itself. How can I avoid throwing error if no match?
2. Why is the above record not matching when the date value is between begDate and endDate?
You are probably doing the same error than in you other question of yesterday: firebase realtime DB querying date between 2 dates does not match anything
Therefore, the reason is probably because begDate and endDate are numbers but you store _date as a string in your database.
Try using toISOString when you save to fb
var _date = new Date().toISOString()
and
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();
var day = d.getDate();
var begDate = new Date(year - 1, month, day).toISOString();
var endDate = new Date(year + 1, month, day).toISOString();

Casting types with Flows comment syntax

I have this function:
([key, value]) => key + "=" + encodeURIComponent(value)
And get the error, that value is mixed but encodeURIComponent expects string.
I'm using Flows comment syntax, so I tried this:
([key, value /*: string */]) => key + "=" + encodeURIComponent(value)
which didn't work.
The type annotation for function params goes between the parameter and the optional default value, e.g.
var fn = (param = 45) => {};
would annotate as
var fn = (param: number = 45) => {};
So in your case [key, value] is param, so the annotation goes after that as
([key, value] /*: [string, string] */) =>

Range of all linkAttributed String in MutableAttributedString in swift

I have a mutableAttributedString in which few strings are linkAttributed,I want to find the Range of all link attributed string. How to do that in swift3 ?
When user start type # in textview i show list of few name. If user select any row then following method gets called.
func didSelectMemberId(_ model: BaseModel) {
var fullName = ""
if model.entityType == ReceiverType.Active.rawValue{
fullName = model.name
}else{
fullName = AtMention + model.name + " " + model.name2
}
let attributedString = NSMutableAttributedString(string:fullName, attributes:[NSFontAttributeName:(appNeedsAutoResize ? (UIUtils.getFontForApproprieteField(.headlineWithoutBold).font) : UIFont.systemFont(ofSize: 14))])
attributedString.addAttribute(NSLinkAttributeName, value: "connectmention://\(model.entityId.stringValue())", range: NSRange(location: 0, length: fullName.length))
attributedString.append(NSAttributedString(string: emptySpaceStringByUC, attributes:[NSFontAttributeName:(appNeedsAutoResize ? (UIUtils.getFontForApproprieteField(.headlineWithoutBold).font) : UIFont.systemFont(ofSize: 14))]))
self.composeBar.textView.textStorage.insert(attributedString, at:self.composeBar.textView.selectedRange.location)
}
self.composeBar.textView.selectedRange = NSMakeRange(self.composeBar.textView.selectedRange.location+fullName.length, 0 )
To get the link proprty I am using the following method
func getlinkActionRange(attributeString: NSAttributedString) -> [MentionStruct] {
var arrMentions = [MentionStruct]()
_ = attributeString.enumerateAttribute(NSLinkAttributeName, in: NSRange.init(location: 0, length: attributeString.length), options: [], using: { (value, range, stop) in
if let url = value {
let occurrence = (attributeString.string as NSString).substring(with:range)
arrMentions.append(MentionStruct(link: url as! String, text: occurrence, range: range))
}
})
return arrMentions
}
If user type anything after inserting that name , that type string also coming.

dealing with a null date field

I have a date field on an XPage, this control may contain a date or be blank. In a repeat control I have this code:
var doc:NotesDocument = detailData.getDocument();
var sDate = doc.getItemValue("ACAutoStart");
doc.recycle()
return "Start Date = " + sDate
If ACAutoStart contains a date then it is displayed as [10/10/2013 12:34:15 AM MDT] if it is blank it displays as []. As I understand it the [] indicates that the result is an array but if I try using sDate[0] there is an error. I can't use getItemValueDateTime as it does not like the null return. How do I get this into a simple string value?
Replace your last line with return "Start Date = " + sDate.firstElement().
doc.getItemValue() returns an object of class java.util.Vector. As it is not an Array you get the first element with firstElement() instead of [0] .
UPDATE:
As you mentioned in your comment it has to work also for empty values and you added try:
var sDate = "";
try {sDate = doc.getItemValue("ACAutoStart").firstElement()} catch (e) {};
return "Start Date = " + sDate
...just as another way (returns converted NotesDateTime to Date):
function getJavaDateData(doc:NotesDocument, field:string)
{
var item:NotesItem = doc.getFirstItem(field);
if (item != null){
var dt:NotesDateTime = item.getDateTimeValue();
if (dt != null){
return dt.toJavaDate();
}
}
return null;
}
Off-course need to be adapted for your logic...

Resources