How to strip/ignore unused attributes when saving a model object? - bookshelf.js

I am sending angular model objects to bookshelf to save, but it may carry extraneous attributes that aren't in the database. When I save, bookshelf will try to save all attributes and say it can't find these extra attributes.
What is the recommended way to handle this? I'm sure I can set out an array of whitelisted attributes, and strip the object manually, but is there another way?
IE, is there a built in way to ignore unused attributes? Or is there a way to query the DB to get the array of columns, then use that to strip my object?

You may use parse() in addition to an array of permitted attributes, like Ghost team did.
Mode = bookshelf.Model.extend({
permittedAttributes: [ 'field1', 'field2', 'field3' ],
parse: function (attrs) {
return _.pick(attrs, this.permittedAttributes)
}
})
If you define parse() in a base model, all models that extend it will behave the same way

Tooting my own horn here, but I encountered this problem so many times that I created a plugin for bookshelf. Didn't want to have to manually define permitted attributes every single time.
https://www.npmjs.com/package/bookshelf-strip-save

Related

How to get away from Non-capitalized key value for Record construction?

I am using graphql, nexus-plugin-prisma, prisma to build a backend application using ReScript. The problem I face is that there are some columns starting with capital letter, and I want to set types for such schemas using records instead of objects. (to make use of pattern matching utility)
But ReScript prevents capitalized letters to appear as the very first character of a key of a record. Is there any way that I can somehow get away with this issue? Any help would be appreciated.
Usually when dealing with graphQL, the best way to circumvent this issue is to make use of graphQL aliasing feature:
fragment Foo on foo {
uncapitalizedAlias: CapitalizedName
}
edit: I don't know if the records you're trying to use are defined beforehand or generated by your GraphQL client, but you have other more general solutions when you want to bind to JS objects with capitalized names:
you can make use bs.as to change the name of the field (works both in Ocaml/Reason and Rescript syntaxes):
type myGQLrecord = {
#bs.as("CapitalizedName")
uncapitalizedName: string,
}
or you can directly use any identifier name you want for your field thanks to this feature of rescript syntax (works also for value identifiers):
type myGQLrecord = {
\"CapitalizedName": string
}
In my opinion, it makes it a bit more cumbersome to use though.

Can a Cerberus schema have an arbitrary name for the base dict?

I need to validate Python dicts that will have arbitrary names. When I attempt to validate them using Cerberus, I get unknown field. Is there a way of allowing for arbitrary dict names?
I was thinking that keysrules might work, but it appears to only work on items within the base dict.
{'account_created': {'category': 'Accounts',
'conversion_event': True,
'description': 'A new account is created'}
}
I would like to be able to use an arbitrary name where account_created is in this dict.
Assuming you don't need to validate that base key, I just attempted to answer a question similar to this on the Cerberus GitHub. My suggestion was to maybe use a dynamically formed schema. You could follow the GitHub issue thread and see if anyone there comes up with a better answer.

Something akin to "Sparse Fieldsets" in .NET

I'm trying to find the vocabulary to describe what I want and if it exists.
I have a table that shows a few data points from large objects. Loading the entire objects just for the table is very slow. Is there a way to only pass to the front the few properties I want without having to define a new object?
I found something called Sparse Fieldsets in JSON API, and I'm wondering if something like this exists for .NET under another name.
Update:
Talking to another coder, I realize it probably makes more sense to implement something like this between the backend and the database and make a specific call for this table. I still need to work out if I need to create a new object to support this. I think it'd still be faster if I just kept the same object but nulled out all of the connecting objects that I don't need for the table. But maybe that's considered bad practice? Also we're using Entity Framework for what it's worth.
Update 2:
I just created a new query without all of the .Include() and works well enough for what I need:
_dataContext.ApplePie
.Include(f => f.Apples).ThenInclude(f => f.Apple)
.Include(f => f.Sugars).ThenInclude(f => f.MolecularStructure)
.Include(f => f.Recipe)
Maybe you are looking for Anonymous Types?
For example, if you had a typed object with three properties, but you only wanted to operate on two:
var threePropThing = new ThreePropertyThing { Id = 1, Message = "test", ExtraProperty = "ex" };
var myAnonThing = new { Id = threePropThing.Id, Message = threePropThing.Message };
Best practice would be to not pass this anonymous object around. But, if you really needed to, you could return it as type object.
Typically, when passing data around in c#, you want to have it typed.
C# is a strongly-typed language and I would say that it is unusual for C# to support scenarios, when object definition (properties) are not known in advance, like in JSON API "fields" parameter case. Implementing this would imply using reflection to filter the properties, which is usually slow and error-prone.
When implementing C# web-services, people usually create one DTO response model per each request.
If your table has fixed set of fields, I would personally recommend to create a DTO class containing only the fields which are required for your table, and then create a method which returns this response for your specific request. While it doesn't align with "without having to define a new object" in the question, it makes the intention clear and makes it really easier to maintain the API in future.
You might want to use libraries like AutoMapper to save time and avoid duplicated code of copying the values from data model to DTO, if you have many such methods.

What is main advantage of Tuple?

Can anyone tell me what is the main advantage of using tuple? In what scenarios do I need to use these?
I assume that you're talking about the Tuple<> type and not anonymous tuple classes.
Like an anonymous type, Tuple<> allows you to avoid declaring a new class just to group a few objects. Unlike anonymous types, tuple types have known names and thus can be used as method return and parameter values, etc.
Personally, I try to avoid heavy use of Tuple<> because it can make for difficult to understand code, expecially when used with primitive types (e. g. if you see a Tuple it's not obvious what each field represents).
One place I have found tuples to be very useful is as dictionary keys. Because Tuples implement Equals() and GetHashCode() (not ==, though!), they are perfect for things like private dictionaries that cache information based on a compound key.
It's used mostly to avoid declaring a class / struct with a few properties only for the sake of passing a group of objects around, where only one object can be passed.
Lets say I have a list of urls to go through and if i get an error (4xx or 5xx) I want to build a list and then either later display it to the user or just look at it in my debugger.
I'd catch the web exception and have a Tuple<string, int> (url, http error code) instead of creating a struct for one or two functions to use. Heck it might even be a foreach loop with a breakpoint on if the list has more then 0 items. Thats when it is useful.

How to store object types and create objects using that information only

I would like to store MetaObjects in a list like this:
myList = QList<QMetaObject>();
myList->append(MyClass::staticMetaObject);
myList->append(MyOtherClass::staticMetaObject);
I want to keep track of these object through out the application but I don't wish to allocate them just yet. By adding some information in my classes I will be able to use the MetaObject function "classInfo(int).value()". I use this when I store them in a QListWidget. When a row in the QListWidget is pressed I would like to be able to create an object of that specific kind that is stored in the list.
(Also have to add that all the classes dervies from the same baseclass)
This sample code describes a bit of what I want to do, except in his example, you add the classes as you go along.
http://lists.qt.nokia.com/pipermail/qt-interest/2012-January/037204.html
I read through the manual and when I try things like:
MyBaseClass *test = qobject_cast<MyBaseClass*>myList->at(i).newInstance();
The project compiles but when I try to print the "test" object its null. What am I doing wrong? And is this the best way of doing this?
Was also looking at MetaType, but where would i be able to store, for example a string for the menus if I'm not allowed to create the object? Would this be a nicer solution if I have a static function that returns a string?
Edit:
I now changed so the constructors are Q_INVOKABLE which solved the problem where "test == null".
But what are the downside of this solution? Should I just use a object factory (the old fashion way with a switch case)?

Resources