Nest.js serializer like Django - django

I am currently using Nest.js, Postgresql, Typeorm for my backend. Now I am trying to do is to see an specific entity field differently by each user.
For example there are 10 posts and one user has bookmarked 3 of them. Only a user who bookmarked the post can get isBookmarked = true, others isBookmarked = false.
I used Django a bit and I used serializer to implement the same logic. I looked for Nest.js serializer (https://docs.nestjs.com/techniques/serialization) but I think it is a bit different than what I thought. Please tell me how to use this serializer as Django does, or any other ways to implement the logic.

Since NestJS is using class-transform you can follow the documentation to achieve what you wants => https://github.com/typestack/class-transformer#additional-data-transformation
import { Transform } from 'class-transformer';
export class Post {
id: number;
#Transform(({ value }) => isBookmarkedByTheUser())
bookmarked: boolean;
}
Something like that ;)

Related

Graphene-Django - how to pass an argument from Query to class DjangoObjectType

First of all, thanks ! it has been 1 year without asking question as I always found an answer. You're a tremendous help.
Today, I do have a question I cannot sort out myself.
Please, I hope you would be kind enough to help me on the matter.
Context: I work on a project with Django framework, and I have some dynamic pages made with react.js. The API I'm using in between is graphQL based. Apollo for the client, graphene-django for the back end.
I want to do a dynamic pages made from a GraphQL query having a set (a declared field in the class DjangoObjectType made from a Django query), and I want to be able to filter dynamically the parent with a argument A, and the set with argument B. My problem is how to find a way to pass the argument B to the set to filter it.
The graphQL I would achieved based on graphQL documentation
query DistributionHisto
(
$id:ID,
$limit:Int
)
{
distributionHisto(id:$id)
{
id,
historical(limit:$limit)
{
id,
date,
histo
}
}
}
But I don't understand how to pass (limit:$limit) to my set in the back end.
Here my schema.py
import graphene
from graphene_django.types import DjangoObjectType
class DistributionType(DjangoObjectType):
class Meta:
model = DistributionTuple
historical = graphene.List(HistoricalTimeSeriesType)
def resolve_historical(self, info):
return HistoricalTimeSeries.objects.filter(
distribution_tuple_id=self.id
).order_by('date')[:2]
class Query(object):
distribution_histo = graphene.List(
graphene.NonNull(DistributionType),
id=graphene.ID(),
limit=graphene.Int()
)
def resolve_distribution_histo(
self, info, id=None, limit=None):
filter_q1 = {'id': id} if id else {}
return DistributionTuple.objects.filter(**filter_q1)
I have tried few things, but I didn't find a way to make it to work so far.
At the moment, as you see, the arg "limit" reaches a dead end in def resolve*, where ideally, it would be pass up to the class DistributionSetHistoType where it would replace the slice [:2] by [:limit] in resolve_distribution_slice_set()
I hope I have been clear, please let me know if it's not the case.
Thanks for your support.
This topic called pagination.
front end seletion
const { loading, error, data, fetchMore } = useQuery(GET_ITEMS, {
variables: {
offset: 0,
limit: 10
},
});
backend selction
the number 10 in .count(10) represent the first 10 elements in the array
DistributionTuple.objects.filter(**filter_q1).count(10)

Validate custom field with Flask-RESTPlus

I'm trying to create a custom field for validating POSTed JSON in my API using Flask-RESTPlus 0.10.1
Below is the basic setup...
from flask_restplus import fields
import re
EMAIL_REGEX = re.compile(r'\S+#\S+\.\S+')
class Email(fields.String):
__schema_type__ = 'string'
__schema_format__ = 'email'
__schema_example__ = 'email#domain.com'
def validate(self, value):
if not value:
return False if self.required else True
if not EMAIL_REGEX.match(value):
return False
return True
I like the way the above documents in Swagger UI, but I can't seem to figure out how to actually use the validate method on it.
Here's how I'm using the custom field.
Json = api.model('Input JSON', {
'subscribers': fields.List(Email),
[...]
})
#api.expect(Json) // validate is globally set to true
def post(self):
pass
I've had luck using
'subscribers': fields.List(fields.String(pattern='\S+#\S+\.\S+')) instead, but this doesn't give me the control to customize the error message, where'd I'd like it to return that the field is not of the email type.
I've also gone on and added a custom validate_payload function (found within http://aviaryan.in/blog/gsoc/restplus-validation-custom-fields.html) that I call again within my POST method (instead of api.expect). This requires me to duplicate some core functionality and call it every time in addition to api.expect to output the proper Swagger documentation and a little bit of finesse to get it to work within nested fields.
It's my understanding that this should work out of box? Am I wrong? What am I missing here?
I appreciate this is a little old but just had the same issue.
It looks like the "validate" actually sat over a python jsonschema impl, if you're still interested in digging, it's available here
That aside - you can configure restplus API to use a better formatchecker as follows: (I also validate date-time and date)
format_checker = FormatChecker(formats=["date-time", "email", "date"])
api_v1 = Api(
app, version='1.4',
title='[Anon]',
description='[Anon] API for developers',
format_checker=format_checker
)

ember js get relationships of relationships

My routes have something like this
return this.store.query('author', {filter:{username : username},
include: 'books, books.readers'})
as we can see author has Many-2-Many relationships with books, book have relationship with reader
How can I include books.reader when run query with author?
Ember Data provides the ability to query for records that meet certain criteria. Calling store.query() will make a GET request with the passed object serialized as query params. This method returns a DS.PromiseArray in the same way as findAll.
So for example in your case author with :username can be changed to the following code:
// GET to /persons?filter[username]=username
this.get('store').query('author', {
filter: {
username: username
}
}).then(function(username) {
// Do something with `username` which can be another filter and whatever else you want, give it a try.
});
Hope it can solve your problem.

Custom Model URL

Is there currently (in the latest builds) a way of specifying a URL on a model-by-model basis? in Ember Data 1.0 beta? I have found some questions on SO and issues on Github around this, but most are out-dated.
For example, I have a model that's called App.PaymentSearchResult and rather than having the request go to /payment_search_results I would like it to go to /payments/search. Where would I override the URL used for a given model (rather than overriding buildURL on the RESTAdapter)?
You can override the the find adapter
but it's kind of hackish, i think however i would take another approach. Idealy you want your Ember models to reflect your backend's models, so why would you need a PaymentSearchResult? When you probably already have a Payment model?
If you need to search in your payment records, why not handle it using query params?
http://emberjs.com/guides/models/finding-records/#toc_querying-for-records
this.store.find('payment', { total: "22" });
Then you want to answer accordingly on the server.
If you want to do a search which returns multiple models, you do this with a manual ajax request.
var self = this;
$.get( "/search", { name: "John", time: "2pm" }, function(result) {
self.store.pushMany(result);
});
PushMany assumes a sane JSON structure.
http://emberjs.com/api/data/classes/DS.Store.html#method_pushMany

Django: How to access the model id's within an AJAX script?

I was wondering what is the correct approach,
Do I create HiddenInput fields in my ModelForm and from the
View I pass in the primaryKey for the models I am about to edit into
the hiddenInput fields and then grab those hiddenInput fields from
the AJAX script to use it like this?
item.load(
"/bookmark/save/" + hidden_input_field_1,
null,
function () {
$("#save-form").submit(bookmark_save);
}
);
Or is there is some more clever way of doing it and I have no idea?
Thanks
It depends upon how you want to implement.
The basic idea is to edit 1. you need to get the existing instance, 2. Save provided information into this object.
For #1 you can do it multiple ways, like passing ID or any other primary key like attribute in url like http://myserver/edit_object/1 , Or pass ID as hidden input then you have to do it through templates.
For #2, I think you would already know this. Do something like
inst = MyModel.objects.get(id=input_id) # input_id taken as per #1
myform = MyForm(request.POST, instance=inst)
if myform.is_valid():
saved_inst = myform.save()
I just asked in the django IRC room and it says:
since js isn't processed by the django template engine, this is not
possible.
Hence the id or the object passed in from django view can't be accessed within AJAX script.