loopback4 Regular Expressions- Match Anything - regex

I use loopback4. How do I make an expression to match datetime with time zone.I am interested by the hour parameter only: "finalhour"
example: 2019-12-20T10:22:50.143Z ==> 2019-12-20Tfinalhour:22:50.143Z
I tried with this: const pattern=await '^'+"T"+finalhour+'^'
but loopback usually read it as ^T10^
I'm resort to you after a long search in the forums.I will be thankful if you help me

From what i understand, you want to build a regex that match 2019-12-20TsomeNumber:22:50.143Z.
You could use this default ISO datetime regex
(\d{4})-(\d{2})-(\d{2})T(\d{2})\:(\d{2})\:(\d{2})\.\d{3,4}Z
And modify it to take your finalhour variable in it.
let finalHour = 10;
// when building regex from constructor, we need to espace the backslash ( \ )
// i did not know that.
let regex = new RegExp('(\\d{4})-(\\d{2})-(\\d{2})T' + finalHour + '\\:(\\d{2})\\:(\\d{2})\\.\\d{3,4}\\Z');
let test = '2019-12-20T10:22:50.143Z';
console.log(regex.test(test));
Also, you don't need an await keyword here because your are building a string, not waiting for a promise.

I need to return the number of order per hour. so i try this solution but it return false comparison, for example if i have one order at hour:10 it return 6
#get('/orders/count-perHour/{date}', {
responses: {
'200': {
description: 'Order model count',
content: { 'application/json': { schema: CountSchema } },
},
},
})
async countPerHour(
#param.path.string('date') date: string): Promise<any> {
let dateStart = new Date(date);
dateStart.setSeconds(0);
dateStart.setMinutes(0);
let dateEnd = new Date(date);
dateEnd.setSeconds(59);
dateEnd.setMinutes(59);
return await this.orderRepository.count(
{
createdAt: {
lte: dateEnd
,
gte: dateStart
}
}
);
}

Related

AdonisJS exists Validator

I'm following the official [documentation] (https://legacy.adonisjs.com/docs/4.0/validator) && indicative, but I couldn't find anything to help me.
I want to validate if the given param exists on database.
So I tried:
app/Validators/myValidator
const { rule } = use('Validator')
get rules () {
return {
userId: 'required|integer|exists:MyDatabase.users,userId', <-- this is what isn't working
date: [
rule('date'),
rule('dateFormat', 'YYYY-MM-DD')
]
}
}
// Getting the data to be validated
get data () {
const params = this.ctx.params
const { userId, date } = params
return Object.assign({}, { userId }, { date })
}
It gives me the following error:
{
"error": {
"message": "select * from `MyDatabase`.`users`.`userId` where `undefined` = '2' limit 1 - ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.`userId` where `undefined` = '2' limit 1' at line 1",
"name": "ErrorValidator",
"status": 40
}
}
How should I properly indicate that I want to compare MyDatabase.users.userid to the given parameter?
After a few hard try/error I stumbled upon the solution.
Just need to follow what is inside hooks.js and pass the values separated by comma, like so:
get rules () {
return {
userId: 'required|integer|exists:MyDatabase,MyTable,columntoCompare',
}
}

Is it possible to build dynamic queries for Amplify Datastore?

I am looking to create a query-builder for my Amplify Datastore.
The function should process an an array of conditions, that need to be applied to the query and return the according Predicate.
This is easily done, if there is only one filter, but I would like to be able to process any amount of filters.
My goal is to be able to write the queries like so:
Datastore.query(Post, *queryBuilder(filters)*)
Where I can pass an array of filters with a filter looking like this:
filter = {
connector: 'or' |
property: rating
predicate: 'gt'
value: 4
}
and the query builder returns the Predicate in the below mentioned format.
I have tried to chain and return multiple functions in the query builder, but I was not able to figure out a pattern for how to create the correct predicate function.
For reference, this is how queries are built according to the docs: https://docs.amplify.aws/lib/datastore/data-access/q/platform/js#predicates
const posts = await DataStore.query(Post, c => c.rating("gt", 4));
and for multiple conditions:
const posts = await DataStore.query(Post, c =>
c.rating("gt", 4).status("eq", PostStatus.PUBLISHED)
);
Let's say we have the model:
type Post #model{
id: ID!
category: String
city: String
content: String
}
And we want to query & filter by city and category by a dynamic amount of variables. Then we can make a function as such on our script:
const fetchData = async props => {
/*
More configurable wrapper for Datastore.query calls
#param props: {model: Model, criteria: [{fieldId, predicate, value}]}.
*/
try {
let criteria;
if (props.criteria && typeof props.criteria === 'object') {
criteria = c => {
props.criteria.forEach(item => {
const predicate = item.predicate || 'eq';
c[item.fieldId](predicate, item.value);
});
return c;
};
} else {
criteria = props.criteria;
}
return await DataStore.query(props.model, criteria);
} catch (e) {
throw new Error(e);
}
}
So now if we want to execute this we can pass the parameters:
// where Post = models.Post
const myResult = fetchData({model: Post, criteria: [
{ fieldId: 'category',
predicate: 'eq',
value: 'news'
},
{
fieldId: 'city',
predicate: 'eq',
value: 'SomeCityName'
}]
})
Unfortunately I do not know of a way to also query linked relationships as you would using a direct graphQL api query while using DataStore and this method I presented only uses implicit AND between criteria.
I don't know if this has changed since you asked the question but, based on the documents, it looks like multiple conditions have an implicit and, but you can explicitly chain them with or/and/not:
const posts = await DataStore.query(Post, c => c.or(
c => c.rating("gt", 4).status("eq", PostStatus.PUBLISHED)
));

getting mongodb entries with mongoose, fires wrong route, returns everything [duplicate]

This question already has answers here:
Use variable with regex to find data in mongodb (Meteor app)
(3 answers)
Closed 2 years ago.
I have been trying to implement a search function on my website but I keep failing.
I am testing the API with Postman but the code below always returns everything there is - regardeless of the conditions I set. Can someone explain to me what my mistake is?
I've seen the other questions here about text-search but the answers match my code - at least as far as I can see.
the controller code:
const db = require("../models");
const IndexArticle = db.article_index;
exports.findAllContaining = (req, res) => {
const term = req.params.term;
const headline = req.query.headline;
var condition = { headline: { $regex: new RegExp(/.+term.+/), $options: "i" } };
IndexArticle.findAll(condition)
.sort({ $natural: -1 }).limit(50)
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving index_articles."
});
});
};
and this is the route
var router = require("express").Router();
//retrieve all published articles containing term
router.get("/?search=:term", article_index.findAllContaining);
I am new to working with the back-end and appreciate any advice.
the model file:
module.exports = mongoose => {
const IndexArticle = mongoose.model(
"indexArticle",
mongoose.Schema(
{
headline: String,
timestamp: String,
tags: [String],
region: String,
proof: Array,
sources: Array,
published: Boolean,
},
{ timestamps: true }
)
);
return IndexArticle;
};
Your regex is wrong. change it to :
var condition = { headline: { $regex: new RegExp(`${term}`), $options: "i" } };
And also change IndexArticle.findAll(condition) to IndexArticle.find(condition).
(your own regex is /.+term.+/ which means : at least one character, then the word term, then at least another character. like: atermb or a term a. )

How to accept comma-separated values in regex pattern Angular

I have a textarea component which accepts these regex patterns:
UserExamble.com,user#,#examble.com,#examble.com
Now i have implemented all above patterns but in textarea, there are supposed to be multiple values seperated by comma, for ex. UserExamble.com,user# or UserExamble.com,user#,#examble.com,#examble.com. This is what i am not able to implement, how can i do this?
Below is my code:
this.userPolicyForm = this.fb.group({
senderRadioBtn: ['Any'],
senderEmailaddress: ['', [Validators.required, Validators.pattern(ValidationPatternConfig.userPolicyEmailAddressPattern)]]
});
and
ValidationPatternConfig.userPolicyEmailAddressPattern=
"^(([^<>()\\[\\]\\\\,;:\\s#\\\"]+(\\.[^<>()\\[\\]\\\\,;:\\s#\\\"]+)*)|(\\\".+\\\")){1,64}#(\\[ipv6:){1}(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\]$"
+"|"+
"^[A-Za-z0-9+.!#$%&'*+/=?^_`{|}~-]{1,64}#\\[(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\]$"
+"|"+
"^(([^<>()\\[\\]\\\\,;:\\s#\\\"]+(\\.[^<>()\\[\\]\\\\,;:\\s#\\\"]+)*)|(\\\".+\\\")){1,64}#((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$"
+"|"+
"^$|^((?!\\.)[\\w-_.]*[^.])(#\\w+)(\\.\\w+(\\.\\w+)?[^.\\W])$"
+"|"+
"^([a-zA-Z0-9!#$%&'*+\\/=?^_`\\{|\\}~\\-.]*[^#,\\]\\[<>:;\"()])#$"
+"|"+
"^#(([a-zA-Z0-9]*([-a-zA-Z0-9]*[a-zA-Z0-9]*)\\.)+[a-zA-Z0-9]*([-a-zA-Z0-9]*[a-zA-Z0-9]))$"
I am using reactive forms in angular.
I have seen few stackoverflow answers, but none of them work. I am new to angular and regex, need help.
One thing you can do is to create custom email validator
this.userPolicyForm = this.fb.group({
senderRadioBtn: ['Any'],
senderEmailaddress: ['', [Validators.required, CustomValidators.validateEmail()]]
});
Create a new file for custom-validator.ts
import { AbstractControl, FormControl } from '#angular/forms';
export class CustomValidators {
// validating array of emails
static validateEmail() {
return (control: FormControl) => {
const pattern = new RegExp('^([a-z0-9\\+_\\-]+)(\\.[a-z0-9\\+_\\-]+)*#([a-z0-9\\-]+\\.)+[a-z]{2,6}$', 'i');
let validEmail = true;
if (control.value !== null) {
const emails = control.value.replace(/\s/g, '').split(',').filter((mail: any) => mail.trim());
for (const email of emails) {
if (email && !pattern.test(email)) {
validEmail = false;
}
}
}
return validEmail ? null : { invalid_email: true };
};
}
}
In html, you can add
<div *ngIf="userPolicyForm.controls.senderEmailaddress.hasError('invalid_email')">
Email address must be valid
</div>
From this you can validate in reactive form. Also when you are submitting array of emails, you can trim it to send to API.
You can decide on the patterns which you want to pass in your textbox and then create regex in 2 parts, one containing the pattern with a comma at the end and a greedy + and second part with just the pattern
like this:
let pattern = "(?:[A-z0-9]+#[A-z]+\.[A-z]{2,6})|(?:[A-z0-9]+#[A-z]+)|(?:#[A-z0-9]+\.[A-z]{2,6})|(?:[A-z0-9]\.[A-z]{2,6})"
var regexPattern = '/(?:' + pattern + '[,])+' + pattern + '/'
var regex = new RegExp(regexPattern)
console.log("UserExamble.com,user#some.com,#examble.com,run.com", regex.test("UserExamble.com,user#some.com,#examble.com,run.com"))
you can use this single regex to validate the input.

Swift: Finding an Object Property via regex

Target: The following function shall iterate over an array of objects and check a specific property of all objects. This property is a string and shall be matched with a user input via regex. If there's a match the object shall be added to an array which will further be passed to another function.
Problem: I don't know how to set up regex in Swift 3. I'm rather new in Swift at all, so an easily understandable solution would be very helpful :)
How it currently looks like:
func searchItems() -> [Item] {
var matches: [Item] = []
if let input = readLine() {
for item in Storage.storage.items { //items is a list of objects
if let query = //regex with query and item.name goes here {
matches.append(item)
}
}
return matches
} else {
print("Please type in what you're looking for.")
return searchItems()
}
}
This is what Item looks like (snippet):
class Item: CustomStringConvertible {
var name: String = ""
var amount: Int = 0
var price: Float = 0.00
var tags: [String] = []
var description: String {
if self.amount > 0 {
return "\(self.name) (\(self.amount) pcs. in storage) - \(price) €"
} else {
return "\(self.name) (SOLD OUT!!!) - \(price) €"
}
}
init(name: String, price: Float, amount: Int = 0) {
self.name = name
self.price = price
self.amount = amount
}
}
extension Item: Equatable {
static func ==(lhs: Item, rhs: Item) -> Bool {
return lhs.name == rhs.name
}
}
Solved. I just edited this post to get a badge :D
For the purpose of letting the answer to be generic and clear, I will assume that the Item model is:
struct Item {
var email = ""
}
Consider that the output should be a filtered array of items that contains items with only valid email.
For such a functionality, you should use NSRegularExpression:
The NSRegularExpression class is used to represent and apply regular
expressions to Unicode strings. An instance of this class is an
immutable representation of a compiled regular expression pattern and
various option flags.
According to the following function:
func isMatches(_ regex: String, _ string: String) -> Bool {
do {
let regex = try NSRegularExpression(pattern: regex)
let matches = regex.matches(in: string, range: NSRange(location: 0, length: string.characters.count))
return matches.count != 0
} catch {
print("Something went wrong! Error: \(error.localizedDescription)")
}
return false
}
You can decide if the given string does matches the given regex.
Back to the example, consider that you have the following array of Item Model:
let items = [Item(email: "invalid email"),
Item(email: "email#email.com"),
Item(email: "Hello!"),
Item(email: "example#example.net")]
You can get the filtered array by using filter(_:) method:
Returns an array containing, in order, the elements of the sequence
that satisfy the given predicate.
as follows:
let emailRegex = "[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailItems = items.filter {
isMatches(emailRegex, $0.email)
}
print(emailItems) // [Item(email: "email#email.com"), Item(email: "example#example.net")]
Hope this helped.
You can do the same with filter function
let matches = Storage.storage.items.filter({ $0.yourStringPropertyHere == input })