Query Parameters in case class - Swagger Docs - scala

I am writing an API for my application.
The application allows administrators to search for users with query params.
My problem
There are a lot of query parameters which are using a lot space in my controllers. Currently I have solved it by having all the QueryParameters as parameters in the method, like this:
def findUser (
#ApiParam(name = "firstName", value = "First name", `type` = "query")
#RequestParam(value = "firstName", required = false) firstName: String,
#ApiParam(name = "surname", value = "Surname", `type` = "query")
#RequestParam(value = "surname", required = false) surname: String,
#ApiParam(name = "email", value = "Email adress", `type` = "query")
#RequestParam(value = "email", required = false) email: String,
#ApiParam(name = "telephoneNumber", value = "Phone number", `type` = "query")
#RequestParam(value = "telephoneNumber", required = false) telephoneNumber: String,
#ApiParam(name = "landlineNumber", value = "Land line number", `type` = "query")
#RequestParam(value = "landlineNumber", required = false) landlineNumber: String,
#ApiParam(name = "dateOfBirth", value = "Date of Birth", `type` = "query")
#RequestParam(value = "dateOfBirth", required = false) dateOfBirth: String,
#ApiParam(name = "postalAddress", value = "Postal adress", `type` = "query")
#RequestParam(value = "postalAddress", required = false) postalAddress: String,
#ApiParam(name = "postCode", value = "Post code", `type` = "query")
#RequestParam(value = "postCode", required = false) postCode: String
) = {
// doing stuff
}
Question:
Is there a way to extract all the query params into a class or a object in Swagger Docs? Like illustrated below:
def allQueryParamsInACaseClass (
queryParams : AllQueryParams
)

I fixed it by using #ModelAttribute and then created a case class with #BeanProperties.
def allQueryParamsInACaseClass (
#ModelAttribute queryParams: AllQueryParams
)
case class AllQueryParams (
...
#ApiParam(name = "firstName", value = "First name", `type` = "query")
#RequestParam(value = "firstName", required = false) #BeanProperty firstName: String,
..
)

Related

Why am I getting Dart Error: Undefined name 'yas'?

main() {
CarsB cars = CarsB(lastname: 'Uysal', firstname: 'Kerem');
print(cars.firstname);
}
class Cars {
String firstname = '';
String lastname = '';
int yas = 0;
Cars(
this.yas, {
this.firstname = '',
this.lastname = '',
});
}
class CarsB extends Cars {
CarsB({String firstname = '', String lastname = ''})
: super(yas, firstname: firstname, lastname: lastname);
}
Why am I getting an error?
Error is:
Error: Undefined name 'yas'.
main.dart:51
: super(yas, firstname: firstname, lastname: lastname);
^^^
Exited (254)
CarsB({String firstname = '', String lastname = ''})
: super(yas, firstname: firstname, lastname: lastname);
Your CarsB constructor does not have a parameter called yas. So passing yas to the super constructor is a mistake. The compiler does not know what to do with it. When I call final b = CarsB(firstname: 'John', lastname: 'Doe'); what do you expect yas to be? It is undefined. And your compiler cannot compile that.

Flask SQLAlchemy, IntegrityError, ForeignKeyViolation - Creating relationships between tables

I'm trying to create a Flask app where I can return a list of 'workspaces' from a postgresql database, a list of 'categories and a list of 'projects'.
In projects.py, when a GET method is called, the database will return all of the 'workspaces' and all of the 'categories' and get both the id and name for each, I can then put this in a dropdown button for the user to select. This part of the code works fine.
When a POST method is called, this should add a new row to the 'projects' table to define a new project, along with this should be the workspace_id and the categories_id that the user selected.
This part of the code is not working, I get the following error message:
sqlalchemy.exc.IntegrityError: (psycopg2.errors.ForeignKeyViolation) insert or update on table "projects" violates foreign key constraint "workspace_id"
DETAIL: Key (id)=(19) is not present in table "workspaces".
[SQL: INSERT INTO projects (name, description, category_id, workspace_id, visibility_level, slug) VALUES (%(name)s, %(description)s, %(category_id)s, %(workspace_id)s, %(visibility_level)s, %(slug)s) RETURNING projects.id]
[parameters: {'name': 'Brand New Project', 'description': 'gfhfghfg', 'category_id': '1', 'workspace_id': '1', 'visibility_level': '1', 'slug': 'brand-new-project'}]
models.py:
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from taskmanagement.database import Base
class Projects(Base):
__tablename__ = 'projects'
id = Column(Integer, primary_key=True)
name = Column(String(140), unique=True)
description = Column(String(140), unique=True)
category_id = Column(Integer, ForeignKey('categories.id'), unique=False, nullable=False)
category = relationship('Categories', lazy=True, uselist=False, primaryjoin="Categories.id == Projects.category_id")
workspace_id = Column(Integer, ForeignKey('workspaces.id'), unique=False, nullable=False)
workspace = relationship('Workspaces', lazy=True, uselist=False, primaryjoin="Projects.workspace_id == Workspaces.id")
visibility_level = Column(Integer, unique=False)
slug = Column(String(240), unique=True)
def __init__(self, name=None, description=None, category_id=None, workspace_id=None, visibility_level=None, slug=None):
self.name = name
self.description = description
self.category_id = category_id
self.workspace_id = workspace_id
self.visibility_level = visibility_level
self.slug = slug
def __repr__(self):
return f'<Projects {self.name!r}>'
class Workspaces(Base):
__tablename__ = 'workspaces'
id = Column(Integer, primary_key=True)
name = Column(String(50), unique=True)
def __init__(self, name=None):
self.name = name
def __repr__(self):
return f'<Workspaces {self.name!r}>'
class Categories(Base):
__tablename__ = 'categories'
id = Column(Integer, primary_key=True)
name = Column(String(50), unique=True)
def __init__(self, name=None):
self.name = name
def __repr__(self):
return f'<Workspaces {self.name!r}>'
Projects.py
#projects.route('/projects/add', methods = ['POST', 'GET'])
def project_add():
if request.method == 'GET':
categories = Categories.query.all()
workspaces = Workspaces.query.all()
categories_results = [
{
"id": category.id,
"name": category.name
} for category in categories]
workspaces_results = [
{
"id": workspace.id,
"name": workspace.name
} for workspace in workspaces]
results = {"categories": categories_results, "workspaces": workspaces_results}
return render_template('project_add.html', title='Add Project', results=results)
else:
name = request.form['project_name']
slug = request.form['project_slug']
description = request.form['project_desc']
visibility_level = request.form['project_visibility']
category_id = request.form['category_id']
workspace_id = request.form['workspace_id']
form_results = {
"name": request.form['project_name'],
"slug": request.form['project_slug'],
"description": request.form['project_desc'],
"visibility_level": request.form['project_visibility'],
"category_id": request.form['category_id'],
"workspace_id": int(request.form['workspace_id'])
}
#return form_results
results = Projects(name, description, category_id, workspace_id, visibility_level, slug)
db_session.add(results)
db_session.commit()
I'm completely stuck of this problem. Can anyone tell me what I'm doing wrong?

Return Django ORM union result in Django-Graphene

I am trying to query two separate objects and return them as a single result set. I've tried using a Union and an Interface, but not sure what I'm doing wrong there.
My model:
class BaseActivity(models.Model):
class Meta:
abstract = True
name = models.CharField(db_column="activity_type_name", unique=True, max_length=250)
created_at = CreationDateTimeField()
modified_at = ModificationDateTimeField()
created_by = models.UUIDField()
modified_by = models.UUIDField()
deleted_at = models.DateTimeField(blank=True, null=True)
deleted_by = models.UUIDField(blank=True, null=True)
class Activity(BaseActivity):
class Meta:
db_table = "activity_type"
ordering = ("sort_order",)
id = models.UUIDField(
db_column="activity_type_id",
primary_key=True,
default=uuid.uuid4,
editable=False,
)
sort_order = models.IntegerField()
def __str__(self):
return self.name
class CustomActivity(BaseActivity):
class Meta:
db_table = "organization_custom_activity_type"
id = models.UUIDField(
db_column="organization_custom_activity_type",
primary_key=True,
default=uuid.uuid4,
editable=False,
)
farm = models.ForeignKey("farm.Farm", db_column="organization_id", on_delete=models.DO_NOTHING, related_name="custom_activity_farm")
My schema:
class FarmActivities(graphene.ObjectType):
id = graphene.String()
name = graphene.String()
class ActivityType(DjangoObjectType):
class Meta:
model = Activity
fields = ("id", "name", "requires_crop", "sort_order")
class CustomActivityType(DjangoObjectType):
class Meta:
model = CustomActivity
fields = ("id", "name", "farm")
And the query:
class Query(graphene.ObjectType):
get_farm_activities = graphene.Field(FarmActivities, farm=graphene.String(required=True))
def resolve_get_farm_activities(self, info, farm):
farm_activities = Activity.objects.values("id", "name").filter(
farmtypeactivityrel__farm_type__farm=farm, deleted_at=None
)
custom_activities = CustomActivity.objects.values("id", "name").filter(farm=farm, deleted_at=None)
return list(chain(farm_activities, custom_activities))
With this, I do get a list back from the query, but it's not going thru the resolver when I call getFarmActivities.
Literally the list returns:
ExecutionResult(data={'getFarmActivities': {'id': None, 'name': None}}, errors=None)
How to resolve graphene.Union Type?
That provided the hint I needed to get this working. I had to build a Union that would parse the model and not the schema type.
class FarmActivities(graphene.Union):
class Meta:
types = (ActivityType, CustomActivityType)
#classmethod
def resolve_type(cls, instance, info):
if isinstance(instance, Activity):
return ActivityType
if isinstance(instance, CustomActivity):
return CustomActivityType
return FarmActivities.resolve_type(instance, info)
Which then allowed me to run the query like so:
def resolve_get_farm_activities(self, info, farm):
farm_activities = Activity.objects.filter(
farmtypeactivityrel__farm_type__farm=farm
)
custom_activities = CustomActivity.objects.filter(farm=farm)
return list(chain(farm_activities, custom_activities))
And the API query:
query farmParam($farm: String!)
{
getFarmActivities(farm: $farm)
{
... on CustomActivityType
{
id
name
}
... on ActivityType
{
id
name
}
}
}

Using value/variable used in if.clause after the if

I want to create a new address model. Doing so, beforehand I check a data structure if this contains specific information and then extract them and store it into a variable. After all if-clauses I want to use these variables to create a new object of type Address. However, all the in-between stored variables are not recognized:
final List type = c['types'];
if (type.contains('street_number')) {
final streetNumber = c['long_name'];
}
if (type.contains('route')) {
final street = c['long_name'];
}
if (type.contains('locality')) {
final city = c['long_name'];
}
if (type.contains('postal_code')) {
final zipCode = c['long_name'];
}
final address = Address(
country: null,
postalCode: zipCode, //Undefinex name 'zipCode'
city: city,
streetNumber: streetNumber,
long: null,
lat: null);
});
Variables which are declared in a code block will be removed after that block. So you have to declare that Variables before those blocks:
dynamic streetNumber;
if (type.contains('street_number')) {
streetNumber = c['long_name'];
}
dynamic street;
if (type.contains('route')) {
street = c['long_name'];
}
dynamic city;
if (type.contains('locality')) {
city = c['long_name'];
}
dynamic zipCode;
if (type.contains('postal_code')) {
zipCode = c['long_name'];
}

Spring MyBatis conversion error

I am quite new to Spring with MyBatis, and I encountered this error. I am trying to upload an image to my database which is MySQL
Failed to convert value of type 'java.lang.String' to required type 'org.springframework.web.multipart.commons.CommonsMultipartFile'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.springframework.web.multipart.commons.CommonsMultipartFile]: no matching editors or conversion strategy found
This is my controller:
#RequestMapping(value = "/GalleryResults", method = RequestMethod.GET)
public String insert(Model model,
#RequestParam(value = "photo", required = false) CommonsMultipartFile photo,
#RequestParam(value = "caseNo", required = false) String caseNo,
#RequestParam(value = "date", required = false) String date,
#RequestParam(value = "offenseIncident", required = false) String offenseIncident,
#RequestParam(value = "nameAKA", required = false) String nameAKA,
#RequestParam(value = "height", required = false) String height,
#RequestParam(value = "built", required = false) String built,
#RequestParam(value = "otherInfo", required = false) String otherInfo,
#RequestParam(value = "describedBy", required = false) String describedBy,
#RequestParam(value = "requestingParty", required = false) String requestingParty,
#RequestParam(value = "investOnCase", required = false) String investOnCase,
#RequestParam(value = "interviewer", required = false) String interviewer,
#RequestParam(value = "age", required = false) String age,
#RequestParam(value = "weight", required = false) String weight,
#RequestParam(value = "complexion", required = false) String complexion,
#RequestParam(value = "rating", required = false) String rating) {
try {
GalleryResults input = new GalleryResults();
input.setCaseNo(caseNo);
input.setDate(date);
input.setOffenseIncident(offenseIncident);
input.setNameAKA(nameAKA);
input.setHeight(height);
input.setBuilt(built);
input.setOtherInfo(otherInfo);
input.setDescribedBy(describedBy);
input.setRequestingParty(requestingParty);
input.setInvestOnCase(investOnCase);
input.setInterviewer(interviewer);
input.setAge(age);
input.setWeight(weight);
input.setComplexion(complexion);
input.setRating(rating);
input.setPhoto(photo);
input.setPhotoBytes(photo.getBytes());
input.setPhotoContentType(photo.getContentType());
input.setPhotoName(photo.getOriginalFilename());
galleryService.create(input);
} catch (Exception e) {
}
return "galleryResults";
}
My POJO
private CommonsMultipartFile photo;
private byte[] photo;
private byte[] photoBytes;
private String photoName;
private String photoContentType;
Is there anything that I did wrong? Or am I missing anything?
When a file upload, the HTTP request which is sended to web server like
POST /someUrl
Content-Type: multipart/mixed
--edt7Tfrdusa7r3lNQc79vXuhIIMlatb7PQg7Vp
Content-Disposition: form-data; name="meta-data"
Content-Type: application/json; charset=UTF-8
Content-Transfer-Encoding: 8bit
{
"name": "value"
}
--edt7Tfrdusa7r3lNQc79vXuhIIMlatb7PQg7Vp
Content-Disposition: form-data; name="file-data"; filename="file.properties"
Content-Type: text/xml
Content-Transfer-Encoding: 8bit
... File Data ...
The part named "File Data" represent the real file data stream. It is convert to "MultipartFile" by #RequestPart("file-data"). The method which handle the upload logic should be like this:
#RequestMapping("/../upload")
public void uploadFile(#RequestPart("file-data") MultipartFile uploadedFile, ..) {
......
}
Add the conversion strategy for
org.springframework.web.multipart.commons.CommonsMultipartFile
in bean