awslabs / dynamodb-data-mapper-js

A schema-based data mapper for Amazon DynamoDB.
https://awslabs.github.io/dynamodb-data-mapper-js/
Apache License 2.0
817 stars 106 forks source link

Using arguments in the constructor #191

Open rasovica opened 4 years ago

rasovica commented 4 years ago

I am trying to create a class that extends a Base class which provides helpers for .get() and similar. My original idea was to have the constructor set the attributes of the class instead of having to call Object.assign everywhere. For some reason the mapper annotation does not permit arguments in the constructor (ZeroArgumentsConstructor). What is the reason for this?

As it is now I have to do some magic stuff that typescript isn't happy about. Here is a slim version:

class Base<T extends Base<T>> {
    static create(attrs) {
        return Object.assign(new this(), attrs);
    }

    put()  {
        return mapper.put(this);
    }
}

@table('something')
class User extends Base<User> {
    @hashKey()
    email: string;
}

This valid in typescript but the issue is that the return type of create is any as you can't use generics in static neither can you use new this() in a already instanced object.

If there is a better way to do this I would happily do it. But this syntax seems way cleaner than the Object.assign pattern.

await User.create({
    email,
}).get();