Nested DTO's not working with NestJS Swagger - express

Im trying to use swagger in my new nestjs project.
I use DTO to serialize response but i wanted use it also for swagger and almost everything is ok. Lessons value in swagger is just "lessons":["string"] where it should be lesson object with three key:value pairs.
I don't want to use example param to manual define lesson object because i think it might be complicated in larger apps.
Swagger Example Response
{
"totalDocs": 0,
"limit": 0,
"totalPages": 0,
"page": 0,
"pagingCounter": 0,
"hasPrevPage": true,
"hasNextPage": true,
"docs": {
"title": "string",
"description": "string",
"lessons": [
"string"
],
"price": 0,
"isFree": false,
"published": false,
"slug": "string",
"createdAt": "2022-11-14T22:33:42.608Z",
"updatedAt": "2022-11-14T22:33:42.608Z"
}
}
UserCouse.response.dto.ts
class Lesson {
#ApiProperty({ description: 'Lesson ID' })
#Expose()
_id: string;
#ApiProperty({ description: 'Lesson name' })
#Expose()
name: string;
#ApiProperty({ description: 'Lesson type' })
#Expose()
type: string;
}
class Course {
#ApiProperty({ description: 'Course ID' })
#Expose()
_id: string;
#ApiProperty({ description: 'Course title' })
#Expose()
title: string;
#ApiProperty({ description: 'Course description' })
#Expose()
description: string;
#ApiProperty({ description: 'Course slug' })
#Expose()
slug: string;
#ApiProperty({ description: 'Course lessons', type: Lesson, isArray: true })
#Expose()
#Type(() => Lesson)
lessons: Lesson[];
#Expose()
#ApiProperty({
description: 'Course lesson count',
example: 8,
})
lessonsCount: number;
}

Fixed!
Dto class name must contain DTO in name. So in my example it’s LessonDTO.

Related

How to do Prisma runtime model validation?

In my application, I have validated the input credential at the DTO level by using class-validator. But I need runtime model validation like sequelize ORM.
In sequelize:
'use strict';
import { DataTypes, Sequelize } from 'sequelize';
function User(sequelize: Sequelize) {
const user = sequelize.define(
'User',
{
name: {
type: DataTypes.STRING,
allowNull: false
},
role: {
type: DataTypes.STRING(20),
allowNull: false
},
email: {
type: new DataTypes.STRING,
allowNull: false,
validate: {
isEmail: {
// args: true,
msg: 'Invalid email'
},
len: {
args: [1, 100] as readonly [number, number],
msg: 'Email length should be 1 to 100 characters'
},
notNull: {
// args: true,
msg: 'Email cannot be empty'
}
}
},
password: {
type: DataTypes.VIRTUAL,
allowNull: true,
},
},
{
tableName: 'users',
underscored: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
deletedAt: 'deleted_at',
paranoid: true
}
);
return user;
}
export default User;
Is there any possibility to do model validation in Prisma?
There is an open feature request for Prisma to support runtime model validation directly at the Schema level. Alternatively, you can leverage the Client Extensions to perform validation. There is an example in this blog post that shows how to perform custom runtime validation.

Counting in Many-To-Many Relations Sequelize

I am trying to count number of Followers and Followings of a user.
as followingCount and followerCount
User Model
User.init(
{
id: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
},
email: {
type: DataTypes.STRING,
},
password: {
type: DataTypes.STRING,
},
}
);
static associate(models) {
// Follow relationship
this.belongsToMany(models.User, {
through: 'UserFollow',
foreignKey: 'followerId',
as: 'following',
});
// Follow relationship
this.belongsToMany(models.User, {
through: 'UserFollow',
foreignKey: 'followeeId',
as: 'follower',
});
}
Where UserFollow is a Joint Table with columns followeeId and followerId.
My current approach for finding number of followings is something like this :
const user = await User.findOne({
where: {
id,
},
attributes: [
'id',
'userName',
'email',
[sequelize.fn('COUNT', sequelize.col('following->UserFollow.followeeId')), 'followingCount'],
],
include: [
{
model: User,
as: 'following',
attributes: ['id', 'userName', 'email'],
through: {
attributes: [],
},
},
],
group: ['User.id', 'following.id'],
});
return user;
And Output getting is like this:
Here I am getting followingCount as 1... but it should be 3.
"data": {
"id": "1af4b9ea-7c58-486f-a37a-e46461487b06",
"userName": "xyz",
"email": "xyz#gmail.com",
"followingCount": "1", <------ I want this to be 3
"following": [
{
"id": "484202b0-a6d9-416d-a8e2-6681deffa3d1",
"userName": "uqwheuo",
"email": "uqwheuo#gmail.com"
},
{
"id": "56c8d9b0-f5c6-4b2e-b32c-be6363294614",
"userName": "aiwhroanc",
"email": "aiwhroanc#gmail.com"
},
{
"id": "9a3e4074-c7a0-414e-8df4-cf448fbaf5fe",
"userName": "iehaocja",
"email": "iehaocja#gmail.com"
}
]
}
I am not able to count in Joint Table..
The reason that you are getting followingCount: 1 is that you group by following.id (followeeId). It only counts unique followeeId which is always 1.
Although, if you take out following.id from group, the SQL doesn't work any more. It will crash with "a column must appear in GROUP BY clause...". This is a common issue in Postgres and this link (https://stackoverflow.com/a/19602031/2956135) explains the topic well in detail.
To solve your question, instead of using group, you can use COUNT OVER (PARTITION BY).
const user = await User.findOne({
where: {
id,
},
attributes: [
'id',
'userName',
'email',
[Sequelize.literal('COUNT("following->UserFollow"."followeeId") OVER (PARTITION BY "User"."id")'), 'followingCount']
],
include: [
{
model: User,
as: 'following',
attributes: ['id', 'userName', 'email'],
through: {
attributes: [],
}
},
],
});
======================================================
Update:
The original query only fetch "following" relationship. In order to fetch followers of this user, you first need to add "follower" association.
Then, since 2 associations is added, we need to add 1 more partition by column to count exactly the followers or followees.
const followeeIdCol = '"following->UserFollow"."followeeId"';
const followerIdCol = '"follower->UserFollow"."followerId"';
const user = await User.findOne({
where: {
id,
},
attributes: [
'id',
'userName',
'email',
// Note that the COUNT column and partition by column is reversed.
[Sequelize.literal(`COUNT(${followeeIdCol}) OVER (PARTITION BY "Users"."id", ${followerIdCol})`), 'followingCount'],
[Sequelize.literal(`COUNT(${followerIdCol}) OVER (PARTITION BY "Users"."id", ${followeeIdCol})`), 'followerCount'],
],
include: [
{
model: User,
as: 'following',
attributes: ['id', 'userName', 'email'],
through: {
attributes: [],
}
},
{
model: User,
as: 'follower', // Add follower association
attributes: ['id', 'userName', 'email'],
through: {
attributes: [],
}
},
],
});

How do I query for tag names with :find in SnapshotStore store config

I am trying to setup a filter that is similar to a defect view within a Trend chart. The filter in the defect view is:
(State < Closed) AND (Severity <= Major) AND (Tags !contains Not a Stop Ship)
I cannot seem to get the Tags find to work correctly. Any suggestions?
this.myTrendChart = Ext.create('Rally.ui.chart.Chart', {
storeType: 'Rally.data.lookback.SnapshotStore',
storeConfig: {
find: {
_TypeHierarchy: "Defect",
State: {
$lt: "Closed"
},
Severity: {
$lte: "Major"
},
Tags: {
$ne: "Not a Stop Ship"
},
_ProjectHierarchy: ProjectOid
},
hydrate: ["Priority"],
fetch: ["_ValidFrom", "_ValidTo", "ObjectID", "Priority"]
},
calculatorType: 'My.TrendCalc',
calculatorConfig: {},
chartConfig: {
chart: {
zoomType: 'x',
type: 'line'
},
title: {
text: 'Defects over Time'
},
xAxis: {
type: 'datetime',
minTickInterval: 3
},
yAxis: {
title: {
text: 'Number of Defects'
}
}
}
});
Based on reviewing the JSON messages, I figured out the tag needed to be the ObjectId. Once I found this, I replaced "Not a Stop Ship" with the ObjectId value and the filter worked correctly.

Generate items in Ext.dataview.List from hasMany models the MVC way

I have a Blog model with hasMany Posts (and many other fields). Now I want to list these posts in a List-view like that:
[My post #1]
[My post #2]
[My post #3]
As far as the API described, I'm able to pass either a store or a data attribute to Ext.dataview.List. But I was not able to find out how to pass the hasMany records to the list so it will display an item for each of them.
Do I really have to create another store? Isn't it possible to configure my dataview to something like store: 'Blog.posts' or data: 'Blog.posts' or even records: 'Blog.posts'?
Extend the dataview.List to define the itemtpl to loop through the posts
itemTpl: new Ext.XTemplate(
'<tpl for="**posts**" >',
'<div>{TheBlogPost}</div>',
'</tpl>'
)
As #Adam Marshall said, this doesn't work as easy as I imagined.
Sencha autogenerates stores from associations if you know how to access them.
So you simply can switch out the list's store for the autogenerated "substore" when it has loaded.
This approach probably has some problems, e.g. when listpaging plugin is used, but it is quick.
Example:
MODELS
Ext.define('Conversation', {
extend: 'Ext.data.Model',
config: {
fields: [
],
associations:
[
{
type: 'hasMany',
model: "Message",
name: "messages",
associationKey: 'messages'
}
]
}
});
Ext.define('Message' ,
{
extend: "Ext.data.Model",
config: {
idProperty: 'id_message',
fields: [
{ name: 'text', type: 'string' },
{ name: 'date', type: 'string' },
{ name: 'id_message', type: 'int' },
{ name: 'me', type: 'int'} // actually boolean
]
}
}
);
JSON
[
{
"messages": [
{"id_message": 11761, "date": 1378033041, "me": 1, "text": "iiii"},
{"id_message": 11762, "date": 1378044866, "me": 1, "text": "hallo"}
]}
]
CONTROLLER
this.getList().getStore().load(
{
callback: function(records, operation, success) {
//IMPORTANT LINE HERE:
getList().setStore(Ext.getStore(me.getList().baseStore).getAt(0).messages());
},
scope: this
}
);
LIST-VIEW
{
flex: 1,
xtype: 'list',
itemId: 'ConversationList',
data: [],
store: 'ConversationStore',
baseStore: 'ConversationStore',
itemTpl:
' {[app.util.Helpers.DateFromTimestamp(values.date)]}<br><b>{name}</b>' +
' {[app.util.Helpers.fixResidualHtml(values.text)]} </div>' +
},

How to use inner properties of a JSON response with Sencha Proxy

The JSONP proxy is largely working for me, but I need to set properties of a model based on some nested properties in the JSON response. I can't figure how to do this without extending the Reader class, but thought there might be an easier way that I'm just missing.
My Recipe model:
Ext.define('NC.model.Recipe', {
extend: 'Ext.data.Model',
config: {
fields: [
{ name: 'name', type: 'string' },
{ name: 'image', type: 'string' },
{ name: 'preparationText', type: 'string' },
{ name: 'ingredientsText', type: 'string' },
{ name: 'servings', type: 'string' }
]
}
});
My Store:
Ext.define('NC.store.Recipes', {
extend: 'Ext.data.Store',
config: {
model: 'NC.model.Recipe',
storeId: 'Recipes',
proxy: {
type: 'jsonp',
url: 'http://anExternalSite.com/api',
callbackKey: 'callback',
filterParam: 'text',
extraParams: {
type: 'Recipe'
},
reader: {
type: 'json',
idProperty: 'uuid',
}
}
}
});
The JSON format:
[
{
uuid: "/UUID(XXXX)/",
name: "Spicy Peanut Noodle Salad",
image: "http://someplace.com/noodle-salad.jpg",
properties: {
preparationText: "Make it all nice and stuff",
ingredientsText: "Heaps of fresh food",
servings: "serves 4",
}
},
{ ... },
{ ... }
]
I would like those 3 'properties' - preparationText, ingredientsText, and servings, to be placed in the model, but currently only id, name, and image are. What is the method to make this work? If it does involve extending the Reader class, some direction would be great.
Thanks.
You can change your code like this to access nested values
{ name: 'preparationText', type: 'string', mapping: 'properties.preparationText' },
This mapping path should start excluding the root element.