Equivalent to MapStruct for NestJS and Node in general - nestjs

Is there an equivalent of MapStruct, the mapping library widely used in Java, but for javascript, and more precisely for typescript. I know these are two very different languages but I like a lot the annototation style used by Mapstruct to map an entity field to another field in the dto, or the way that you can ignore a field, apply some functions to it like compact a firstName and a lastName coming from the entity to a property fullName in a DTO.
Do you know a library in TS allowing me to replicate the Mapstruct behavior, or do you have some suggestions for me to build my own ?

Related

NestJS: Is it possible to reuse same DTO validation with different field names?

It can be noticed that validating bodies and even route/query params can be much simpler, safer and more readable when you use a DTO instead of, for example, a pipe (depending on the case). As a simple example, I like the idea of using a DTO for validation of the id, like in a findOne() route. So, with a class like this
export class IdDto {
#IsInt()
#IsPositive()
id: number;
}
I can have great validation of the (serial) id. And use it in the route handler like this
findOne(#Param() { id }: IdDto)
The problem is when I have, for example, multiple ids as route params. Obviously I have to name them in a different manner, and then I cannot use this DTO anymore. Unless I create a specific DTO for every case like this one, just renaming the fields. Would there be any way to maintain the usage of this DTO (or any other) in situations like these? Or is there really no alternative?
Of course, I could build my own pipe. It's just that the DTO approach is much simpler, and also class-validator decorators automatically show exactly what step of validation failed. But maybe it's the only option, apart from multiple similar DTOs.
Thanks in advance, and best regards.
P.S.: In the case of multiple ids, that I mentioned, it is a bit more complex. But in the case that I still have just a single id, but want to name it differently in the route? The same question applies, in case it may be simpler.
Generally, decorators on dynamic fields in Typescript doesn't really work because there's no field to (easily) bind to at compile time.
Rather than changing the name of the field, if you are looking for a way to better manage the same decorators across different classes, you could use decorator composition and the applyDecorators method to create a single decorator like
export const IdValidator = applyDecorators(
IsInt(),
IsPositive(),
);
And now use #IdValidator() instead of the others. You still have to make multiple classes, but now have a single source for the entire set of decorators for id validation.

How to add "ref" as string name in C#

I want to name my string value 'ref' without any capital letters. Since ref is a value i can't do that.
Is there a way around this?
As you've discovered, ref is a keyword and can't be used directly in this manner. The usual advice is "don't use keywords as names". For things like deserializing JSON which has a property called "ref" you can often get around it with mapping your otherwise-named property to that JSON property with configuration or a property attribute, depending on the JSON serialization library you're using.
But if you really do need to use a keyword as a name like this, or if it's just easier than mucking around with things like serialization libraries, the language does provide a way to do that. Simply prefix the name with an #:
public string #ref { get; set; }
This approach is most commonly seen in things like Razor web pages where we need to specify client-side HTML attributes in server-side C# objects, and a common HTML attribute name is class.

Extending a JOOQ Table class

I have a 'document' table (very original) that I need to dynamically subset at runtime so that my API consumers can't see data that isn't legal to view given some temporal constraints between the application/database. JOOQ created me a nice auto-gen Document class that represents this table.
Ideally, I'd like to create an anonymous subclass of Document that actually translates to
SELECT document.* FROM document, other_table
WHERE document.id = other_table.doc_id AND other_table.foo = 'bar'
Note that bar is dynamic at runtime hence the desire to extend it anonymously. I can extend the Document class anonymously and everything looks great to my API consumers, but I can't figure out how to actually restrict the data. accept() is final and toSQL doesn't seem to have any effect.
If this isn't possible and I need to extend CustomTable, what method do I override to provide my custom SQL? The JOOQ docs say to override accept(), but that method is marked final in TableImpl, which CustomTable extends from. This is on JOOQ 3.5.3.
Thanks,
Kyle
UPDATE
I built 3.5.4 from source after removing the "final" modifier on TableImpl.accept() and was able to do exactly what I wanted. Given that the docs imply I should be able to override accept perhaps it's just a simple matter of an erroneous final declaration.
Maybe you can implement one of the interfaces
TableLike (and delegate all methods to a JOOQ implementation instance) such as TableImpl (dynamic field using a HashMap to store the Fields?)
Implement the Field interface (and make it dynamic)
Anyway you will need to remind that there are different phases while JOOQ builds the query, binds values, executes it etc. You should probably avoid changing the "foo" Field when starting to build a query.
It's been a while since I worked with JOOQ. My team ended up building a customized JOOQ. Another (dirty) trick to hook into the JOOQ library was to use the same packages, as the protected identifier makes everything visible within the same package as well as to sub classes...

Preventing StackOverflowException while serializing Entity Framework object graph into Json

I want to serialize an Entity Framework Self-Tracking Entities full object graph (parent + children in one to many relationships) into Json.
For serializing I use ServiceStack.JsonSerializer.
This is how my database looks like (for simplicity, I dropped all irrelevant fields):
I fetch a full profile graph in this way:
public Profile GetUserProfile(Guid userID)
{
using (var db = new AcmeEntities())
{
return db.Profiles.Include("ProfileImages").Single(p => p.UserId == userId);
}
}
The problem is that attempting to serialize it:
Profile profile = GetUserProfile(userId);
ServiceStack.JsonSerializer.SerializeToString(profile);
produces a StackOverflowException.
I believe that this is because EF provides an infinite model that screws the serializer up. That is, I can techincally call: profile.ProfileImages[0].Profile.ProfileImages[0].Profile ... and so on.
How can I "flatten" my EF object graph or otherwise prevent ServiceStack.JsonSerializer from running into stack overflow situation?
Note: I don't want to project my object into an anonymous type (like these suggestions) because that would introduce a very long and hard-to-maintain fragment of code).
You have conflicting concerns, the EF model is optimized for storing your data model in an RDBMS, and not for serialization - which is what role having separate DTOs would play. Otherwise your clients will be binded to your Database where every change on your data model has the potential to break your existing service clients.
With that said, the right thing to do would be to maintain separate DTOs that you map to which defines the desired shape (aka wireformat) that you want the models to look like from the outside world.
ServiceStack.Common includes built-in mapping functions (i.e. TranslateTo/PopulateFrom) that simplifies mapping entities to DTOs and vice-versa. Here's an example showing this:
https://groups.google.com/d/msg/servicestack/BF-egdVm3M8/0DXLIeDoVJEJ
The alternative is to decorate the fields you want to serialize on your Data Model with [DataContract] / [DataMember] fields. Any properties not attributed with [DataMember] wont be serialized - so you would use this to hide the cyclical references which are causing the StackOverflowException.
For the sake of my fellow StackOverflowers that get into this question, I'll explain what I eventually did:
In the case I described, you have to use the standard .NET serializer (rather than ServiceStack's): System.Web.Script.Serialization.JavaScriptSerializer. The reason is that you can decorate navigation properties you don't want the serializer to handle in a [ScriptIgnore] attribute.
By the way, you can still use ServiceStack.JsonSerializer for deserializing - it's faster than .NET's and you don't have the StackOverflowException issues I asked this question about.
The other problem is how to get the Self-Tracking Entities to decorate relevant navigation properties with [ScriptIgnore].
Explanation: Without [ScriptIgnore], serializing (using .NET Javascript serializer) will also raise an exception, about circular
references (similar to the issue that raises StackOverflowException in
ServiceStack). We need to eliminate the circularity, and this is done
using [ScriptIgnore].
So I edited the .TT file that came with ADO.NET Self-Tracking Entity Generator Template and set it to contain [ScriptIgnore] in relevant places (if someone will want the code diff, write me a comment). Some say that it's a bad practice to edit these "external", not-meant-to-be-edited files, but heck - it solves the problem, and it's the only way that doesn't force me to re-architect my whole application (use POCOs instead of STEs, use DTOs for everything etc.)
#mythz: I don't absolutely agree with your argue about using DTOs - see me comments to your answer. I really appreciate your enormous efforts building ServiceStack (all of the modules!) and making it free to use and open-source. I just encourage you to either respect [ScriptIgnore] attribute in your text serializers or come up with an attribute of yours. Else, even if one actually can use DTOs, they can't add navigation properties from a child object back to a parent one because they'll get a StackOverflowException.
I do mark your answer as "accepted" because after all, it helped me finding my way in this issue.
Be sure to Detach entity from ObjectContext before Serializing it.
I also used Newton JsonSerializer.
JsonConvert.SerializeObject(EntityObject, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });

How can I combine/split properties with AutoMapper?

we're using Automapper (http://automapper.codeplex.com/) to map between entities and dto's. We have a situation where one property on an entity corresponds to three different properties on the dto, and we need to write some custom logic to do the mapping. Anyone know how we can do that? (We need to map both ways, from entity and from dto).
I notice that AutoMapper supports custom resolvers to do custom mapping logic, but as far as I can tell from the documentation, they only allow you to map a single property to another single property.
Thx
You can create a custom type converter. It allows you to define a converter for an entire type, not just a single property.

Resources