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

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.

Related

Usage of implementsInterface element on entities in guidewire

I would like to know why do we use implementsInterface element in entities. I know one example where they use it to make it as assignable entity. But I could not understand what other purpose and how/why it is being used in entities.
Example: Injuryincident entity has claimantsupplier and coveragesupplier interface
I like to see it from this prespective, simplified and assuming that you have some java background:
As you probably already know it, having an entity means in the end of the day, having a Java class... Well, by using the implementsInterface element in your entity, is similar to implement an interface in you java class.
Here you have a quick example...
Consider the following:
MyEntiti.eti
<?xml version="1.0"?>
<entity
xmlns="http://guidewire.com/datamodel"
entity="MyEntity"
table="myentity"
type="retireable"/>
AnInterface.gs
package mypkg
interface AnInterface {
function doSomething()
}
AnInterfaceImpl.gs
package mypkg
class AnInterfaceImpl implements AnInterface {
override function doSomething() {
print("Hello!")
}
}
Image that you need MyEntity to have the ability of "doSomething", you just need to add the implementsInterface:
<?xml version="1.0"?>
<entity
xmlns="http://guidewire.com/datamodel"
entity="MyEntity"
table="myentity"
type="retireable">
<implementsInterface
iface="mypkg.AnInterface"
impl="mypkg.AnInterfaceImpl"/>
</entity>
By doing that, the following code must work:
var myEntity = new MyEntity()
myEntity.doSomething() //this will call the method defined in the interface-implementation
And even better, you migth let you implementation to recognize the related object of MyEntity and use it as per your needs:
package mypkg
class AnInterfaceImpl implements AnInterface {
private final var _relatedEntity : MyEntity
construct(relatedTo : MyEntity) {
_relatedEntity = relatedTo
}
override function doSomething() {
var createUser = _relatedEntity.CreateUser // you can accees to whatever you need
print("Hello!, this is the related instace of MyEntity: ${_relatedEntity}")
}
}
Hope it helps, regards!
I won't be repeating the other answer describing how it works, but I would like to mention how implementing an interface on an entity is different (and serves different purposes) compared to using enhancements.
On basic level both approaches let you add extra functionality to your entity classes. In most cases what you really want to do is just create/expand an enhancement - they are easier to write, more convenient to modify and just as effective when all you want is to just add a new function or calculated property.
When you implement an interface, you're bringing in some more serious guns. While this approach takes more work and requires creation of several files (not to mention modifying the entity itself), it gives you two important advantages over the enhancement mechanism:
The same interface can be implemented by several entities (typically each having its own implementation class) as well as non-entity classes. Objects of all such classes can then be used interchangeably in contexts expecting the interface (you can create an array of entity instances of several entities and even gosu-only wrappers/temporary objects and present it comfortably in the UI).
You can leverage polymorphism. While enhancement functions can't be overridden, the interface implementations allow you full flexibility of polymorphic OOP. You can, for example, set up a default "do nothing" implementation on high level entity that you intend to use and then add more meaningful implementations for specific subtypes meant to really make use of the new functionality.
It does have some overhead and complicates things, however. As mentioned - Enhancements are typically simpler. In practice you should ask yourself whether the extra effort of creating and implementing the interface is worth it - in many cases even situations seemingly calling for polymorphism can be handled well enough by a simple switch typeof this in the enhancement to provide all the necessary type-based logic.
In personal experience I've used interfaces in quite a few situations, but Enhancements are my first choice in overwhelming majority of cases.
As a final note I'd like to mention a delegate entity. If what you want to add to some unrelated entities is not functionality but Properties with underlying database fields, creating a delegate entity and "implement" it with the desired standalone entities. A delegate entity does work a bit like an interface (you can use entity objects implementing the delegate interchangeably in situations where the delegate is expected) and you can set-up both interface implementation and enhancements on delegate level as well.

Best way to implement ACL with Mongoose

I have my data model already defined and implemented. I can very easily write manually the filter to filter out non-authorized results for the user who sent the query (which would be in the style of: "collection.acl.personId": queryPersonId )
My problem is, where and how should I write this "thing" to be as automatic as possible?
I tried to do it with a custom query and a static method, but did not had any luck on both.
Static method con: I don't want to rewrite all my code to use .then(). I want to keep the current chaining.
Custom query: it simply did not worked, even by following the doc.
Ideal the result would be something like
Model.findWithAcl(filters).lean()
Model.findOneWithAcl(filters).lean()
Note that we are using Typescript. The priority would be to have something working, but having the ability to have a working type would be the second priority right after.
Thanks for any help
Casl mongoose gives a very good way of filtering both results (row level) and fields from collections. Note that it also can be used in the front end.
Great package that works very well with auth0 rights.
https://casl.js.org/v5/en/guide/intro
https://casl.js.org/v5/en/package/casl-mongoose

Retrieving a value object without Aggreteroot

I'm developing an application with Domain Drive Design approach. in a special case I have to retrieve the list of value objects of an aggregate and present them. to do that I've created a read only repository like this:
public interface IBlogTagReadOnlyRepository : IReadOnlyRepository<BlogTag, string>
{
IEnumerable<BlogTag> GetAllBlogTagsQuery(string tagName);
}
BlogTag is a value object in Blog aggregate, now it works fine but when I think about this way of handling and the future of the project, my concerns grow! it's not a good idea to create a separate read only repository for every value object included in those cases, is it?
anybody knows a better solution?
You should not keep value objects in their own repository since only aggregate roots belong there. Instead you should review your domain model carefully.
If you need to keep track of value objects spanning multiple aggregates, then maybe they belong to another aggregate (e.g. a tag cloud) that could even serve as sort of a factory for the tags.
This doesn't mean you don't need a BlogTag value object in your Blog aggregate. A value object in one aggregate could be an entity in another or even an aggregate root by itself.
Maybe you should take a look at this question. It addresses a similar problem.
I think you just need a query service as this method serves the user interface, it's just for presentation (reporting), do something like..
public IEnumerable<BlogTagViewModel> GetDistinctListOfBlogTagsForPublishedPosts()
{
var tags = new List<BlogTagViewModel>();
// Go to database and run query
// transform to collection of BlogTagViewModel
return tags;
}
This code would be at the application layer level not the domain layer.
And notice the language I use in the method name, it makes it a bit more explicit and tells people using the query exactly what the method does (if this is your intent - I am guessing a little, but hopefully you get what I mean).
Cheers
Scott

ServiceStack: Is it expected to create a new class for each return type we expect?

I have a repository class called FooRepository which has the ability to get various objects from a database.
I currently have one business object class called FooObject, which contains all the properties that I care about (Id, Name, CreatedDate, etc)... but my problem is that since ServiceStack only allows one DTO per route, I find myself unable to create more than one API method on my service to get back different types of data from my repository.
So, is it normal in ServiceStack to create a bunch of DTOs that simply return different types of data from the same repository? In ASP/MVC, this is rather easy because there's no route mapping clash going on, and I can simply create 'X' number of methods without the need to tie them to a specific DTO.
Thanks,
-Mario
Yes, each operation should have its own DTO. Keep in mind that the same DTO can be used for different HTTP methods(GET, PUT, POST, DELETE)

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 });

Resources