Get all fields in the Joi schema that are optjonal - hapi.js

How do I get an array or list of field names that were set to optional in Joi object?
For example:
export const schema = Joi.object<SomeType>({
field1: Joi.string().required(),
field2: Joi.string().guid(),
field3: Joi.string().allow('').optional(),
field4: Joi.string().allow('').optional(),
});
I should be able to retrieved field3, field4.
Hapi Joi https://www.npmjs.com/package/#hapi/joi

You can use describe to do so:
Returns an object that represents the internal configuration of the
schema. Useful for debugging and exposing a schema's configuration to
other systems, like valid values in a user interface.
And here we go:
for (const [key, value] of Object.entries(queueSchemaBase.describe().keys)) {
if (value.flags?.presence === 'optional') {
console.log(`${key} is optional`);
}
}
Output:
field3 is optional
field4 is optional

Related

Pydantic: how to make model with some mandatory and arbitrary number of other optional fields, which names are unknown and can be any?

I'd like to represent the following json by Pydantic model:
{
"sip" {
"param1": 1
}
"param2": 2
...
}
Means json may contain sip field and some other field, any number any names, so I'd like to have model which have sip:Optional[dict] field and some kind of "rest", which will be correctly parsed from/serialized to json. Is it possible?
Maybe you are looking for the extra model config:
extra
whether to ignore, allow, or forbid extra attributes during model initialization. Accepts the string values of 'ignore', 'allow', or 'forbid', or values of the Extra enum (default: Extra.ignore). 'forbid' will cause validation to fail if extra attributes are included, 'ignore' will silently ignore any extra attributes, and 'allow' will assign the attributes to the model.
Example:
from typing import Any, Dict, Optional
import pydantic
class Foo(pydantic.BaseModel):
sip: Optional[Dict[Any, Any]]
class Config:
extra = pydantic.Extra.allow
foo = Foo.parse_raw(
"""
{
"sip": {
"param1": 1
},
"param2": 2
}
"""
)
print(repr(foo))
print(foo.json())
Output:
Foo(sip={'param1': 1}, param2=2)
{"sip": {"param1": 1}, "param2": 2}

How will I select a particular object from the array of objects in the mongoose schema?

var mongoose = require("mongoose");
// schema setup
var productSchema = new mongoose.Schema({
type:{
type:String,
required:[true,'a product must have a type']
},
sId:String,
image:String,
products:[{
name:String,
image:String,
price:Number
}]
});
module.exports = mongoose.model("Product",productSchema);
I have made my mongoose schema like this. Now I just want to access a particular object from the array of objects named 'products' using a mongoose query.
Can anyone please tell me how can i do this?? I'll be soo grateful.
You need something like this:
db.collection.find({
"products.name": "name"
},
{
"products.$": 1
})
With this query you will find the product object whose name field is 'name'. Afther that, with the positional operator $ only the matching is returning.
Mongo playground example here
Edit: Note that this query will return multiple subdocuments if exists multiple documents with the array object matching. To filter for a unique element you have to indicate another unique field like this:
db.collection.find({
"sId": "1",
"products.name": "name"
},
{
"products.$": 1
})
Edit to explain how to use find using mongoose.
You can use find or findOne, but the query itself will be the same.
This is pretty simple. You need to use your model described in the question, so the code is somthing like this:
var objectFound = await YourModel.findOne({
"products.name": "name"
},
{
"products.$": 1
})
Where YourModel is the schema defined.

Can I update a FaunaDB document without knowing its ID?

FaunaDB's documentation covers how to update a document, but their example assumes that I'll have the id to pass into Ref:
Ref(schema_ref, id)
client.query(
q.Update(
q.Ref(q.Collection('posts'), '192903209792046592'),
{ data: { text: "Example" },
)
)
However, I'm wondering if it's possible to update a document without knowing its id. For instance, if I have a collection of users, can I find a user by their email, and then update their record? I've tried this, but Fauna returns a 400 (Database Ref expected, String provided):
client
.query(
q.Update(
q.Match(
q.Index("users_by_email", "me#example.com")
),
{ name: "Em" }
)
)
Although Bens comments are correct, (that's the way you do it), I wanted to note that the error you are receiving is because you are missing a bracket here: "users_by_email"), "me#example.com"
The error is logical if you know that Index takes an optional database reference as second argument.
To clarify what Ben said:
If you do this you'll get another error:
Update(
Match(
Index("accounts_by_email"), "test#test.com"
),
{ data: { email: "test2#test.com"} }
)
Since Match could potentially return more then one element. It returns a set of references called a SetRef. Think of setrefs as lists that are not materialized yet. If you are certain there is only one match for that e-mail (e.g. if you set a uniqueness constraint) you can materialize it using Paginate or Get:
Get:
Update(
Select(['ref'], Get(Match(
Index("accounts_by_email"), "test#test.com"
))),
{ data: { email: 'test2#test.com'} }
)
The Get returns the complete document, we need to specify that we require the ref with Select(['ref']..
Paginate:
Update(
Select(['data', 0],
Paginate(Match(
Index("accounts_by_email"), "test#test.com"
))
),
{ data: { email: "testchanged#test.com"} }
)
You are very close! Update does require a ref. You can get one via your index though. Assuming your index has a default values setting (i.e. paging a match returns a page of refs) and you are confident that the there is a single match or the first match is the one you want then you can do Select(["ref"], Get(Match(Index("users_by_email"), "me#example.com"))) to transform your set ref to a document ref. This can then be passed into update (or to any other function that wants a document ref, like Delete).

GraphQL: Use variable value as an alias

I have this GraphQL query:
{
timeline(limit:10){
eventType
level: eventSeverity
},
}
I would like to set the 'eventSeverity' alias name using a variable, rather than the fixed name 'level'. Something like this:
query($name:String!)
{
timeline(limit:10){
eventType
$name: eventSeverity
},
}
But running the above yields this error:
Syntax Error GraphQL request (5:5) Expected Name, found $
Is it possible to use a variable value as an alias name at all?
You cannot use dynamic field name in GraphQL, but what you can do is create a field that accepts a name argument, example
query($name: String!) {
timeline(limit: 10) {
eventType
eventSeverity(name: $name) // Write a resolve function that returns timeline[name]
}
}

PouchDB Query like sql

with CouchDB is possible do queries "like" SQL. http://guide.couchdb.org/draft/cookbook.html says that
How you would do this in SQL:
SELECT field FROM table WHERE value="searchterm"
How you can do this in CouchDB:
Use case: get a result (which can be a record or set of records) associated with a key ("searchterm").
To look something up quickly, regardless of the storage mechanism, an index is needed. An index is a data structure optimized for quick search and retrieval. CouchDB’s map result is stored in such an index, which happens to be a B+ tree.
To look up a value by "searchterm", we need to put all values into the key of a view. All we need is a simple map function:
function(doc) {
if(doc.value) {
emit(doc.value, null);
}
}
This creates a list of documents that have a value field sorted by the data in the value field. To find all the records that match "searchterm", we query the view and specify the search term as a query parameter:
/database/_design/application/_view/viewname?key="searchterm"
how can I do this with PouchDB? the API provide methods to create temp view, but how I can personalize the get request with key="searchterm"?
You just add your attribute settings to the options object:
var searchterm = "boop";
db.query({map: function(doc) {
if(doc.value) {
emit(doc.value, null);
}
}, { key: searchterm }, function(err, res) { ... });
see http://pouchdb.com/api.html#query_database for more info
using regex
import PouchDB from 'pouchdb';
import PouchDBFind from 'pouchdb-find';
...
PouchDB.plugin(PouchDBFind)
const db = new PouchDB(dbName);
db.createIndex({index: {fields: ['description']}})
....
const {docs, warning} = await db.find({selector: { description: { $regex: /OVO/}}})