antd adjusting input value in pagination dropdown - frontend

how can I rid off the '/ page' phrase in dropdown in Pagination in antd ?
regards

In <Pagination/> component, there is attribute called locale.
As per antd implementation, Object called PaginationLocale handles the Options data.
export interface PaginationLocale {
// Options.jsx
items_per_page?: string;
jump_to?: string;
jump_to_confirm?: string;
page?: string;
// Pagination.jsx
prev_page?: string;
next_page?: string;
prev_5?: string;
next_5?: string;
prev_3?: string;
next_3?: string;
}
To change the Lable of option values in the dropdown in Pagination we need to pass object for locale attribute with updated details.
// method to generate value for 'locale'
const getItemsPerPage = () => {
return {
items_per_page: "" // change this to empty string to remove '/ page'
};
};
<Pagination
showSizeChanger
onShowSizeChange={onShowSizeChange}
defaultCurrent={3}
total={500}
locale={getItemsPerPage()} // call 'getItemsPerPage' in render.
/>
With this you can remove '/ page' phrase from dropdown.
Here is the example codesandbox with full demo.

Related

NestJs class-validator accepts empty payload

I'm trying to create validator that accepts 2 values as strings (must exist, min/max length etc).
The issue I am facing is that when I POST empty payload the validation passes and TypeORM tries to insert null values and I end up with HTTP status 500.
When I POST with invalid payload the validation works properly.
I want to get proper validation errors as a response when payload is empty (existence of name property, min/max length etc...) ...
I tried adding various class annotations and global settings but no luck...
Global validation enabled:
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
forbidUnknownValues: true,
skipMissingProperties: false, //Thought this would check for missing properties
transform: true,
}),
);
Entity:
#Entity('r_cat')
export class ResearchCategory {
[...]
#PrimaryGeneratedColumn()
id: number;
#ApiProperty({
description: 'Name of the category',
example: 'Analytics, Integration',
})
#Column('text')
#IsString()
#ApiProperty()
#Length(2, 30)
#IsNotEmpty()
#IsDefined()
name: string;
[...]
My request object (DTO):
export class CreateResearchCategoryRequest extends PartialType(
OmitType(ResearchCategory, ['created_at', 'updated_at', 'deleted_at'] as const),
) {}
Controller:
#Post()
public async create(
#Req() req,
#Body() researchCategory: CreateResearchCategoryRequest,
): Promise<ResearchCategory> {
return await this.service.createNew(researchCategory, req.user);
}
I'm not sure this is the correct way to create a DTO based on the repository class. The usage of the mapper is different from what you've done since Nest examples show is all based on another DTO class, not a repository class.
However, I think the following snippet should work in your situation:
export class CreateResearchCategoryRequest extends OmitType(
ResearchCategory, ['created_at', 'updated_at', 'deleted_at'] as const
) {}

Is it possible to maintain flat input structure with nestjs/graphql Args?

I have a simple query:
#Query(() => ProfileOutput)
async profile(#Args('id') id: string) {
return await this.profileFacade.findProfileById(input.id);
}
The problem is that I want to apply #IsMongoId() from class-validator for the id here. I do not want to create new #InputType here, because I do not want to change API specification. Is there a way to apply validator like #IsMongoId here without the need to change query definition for frontend?
For anyone seeking an answer I found a feature called dedicated argument class. Instead of creating new input type as I thought like this:
#InputType()
export class MongoIdBaseInput {
#IsMongoId()
#Field()
id: string;
}
#Query(() => ProfileOutput)
async profile(#Args('data') input: MongoIdBaseInput) {
return await this.profileFacade.findProfileById(input.id);
}
We can define it almost the same, but annotate input with ArgsType it will maintain flat structure of args for us:
#ArgsType()
export class MongoIdBaseInput {
#IsMongoId()
#Field()
id: string;
}
#Query(() => ProfileOutput)
async profile(#Args() input: MongoIdBaseInput) {
return await this.profileFacade.findProfileById(input.id);
}

How to set default values for DTO in nest js?

I want to set default values for a node in a DTO. So if the value for that node is not passed, a default value will be used. Although this is working, I want the node should be present, the values is optional.
import { IsNotEmpty, IsDefined } from "class-validator";
export class IssueSearch
{
#IsDefined()
search: string;
#IsNotEmpty()
length: number = 10;
#IsNotEmpty()
lastId: string = "0"
}
This doesn't serve my purpose. I want the url to be searched like so
http://base-url/folder?search=value
If the value is not passed it should not throw an error.
But if the param search is not there it should throw an error.
If you want to set a default value go to entity and set in the field for example in mongo db
export class DumpDoc extends Document {
#Prop()
title: string;
#Prop({ default: new Date() }) //set as default
createdAt: string;
}

Nest.js + Mikro-ORM: Collection of entity not initialized when using createQueryBuilder and leftJoin

I'm using Nest.js, and considering migrating from TypeORM to Mikro-ORM. I'm using the nestjs-mikro-orm module. But I'm stuck on something that seems very simple...
I've 3 entities, AuthorEntity, BookEntity and BookMetadata. From my Author module, I try to left join the Book and BookMetadata tables with the createQueryBuilder method. But when running my query, I'm getting an error where Collection<BookEntity> of entity AuthorEntity[3390] not initialized. However columns from the Author table are well retrieved.
My 3 entities:
#Entity()
#Unique({ properties: ['key'] })
export class AuthorEntity {
#PrimaryKey()
id!: number;
#Property({ length: 255 })
key!: string;
#OneToMany('BookEntity', 'author', { orphanRemoval: true })
books? = new Collection<BookEntity>(this);
}
#Entity()
export class BookEntity {
#PrimaryKey()
id!: number;
#ManyToOne(() => AuthorEntity)
author!: AuthorEntity;
#OneToMany('BookMetadataEntity', 'book', { orphanRemoval: true })
bookMetadata? = new Collection<BookMetadataEntity>(this);
}
#Entity()
#Unique({ properties: ['book', 'localeKey'] })
export class BookMetadataEntity {
#PrimaryKey()
id!: number;
#Property({ length: 5 })
localeKey!: string;
#ManyToOne(() => BookEntity)
book!: BookEntity;
}
And the service file where I run my query:
#Injectable()
export class AuthorService {
constructor(
#InjectRepository(AuthorEntity)
private readonly authorRepository: EntityRepository<AuthorEntity>,
) {}
async findOneByKey(props: { key: string; localeKey: string; }): Promise<AuthorEntity> {
const { key, localeKey } = props;
return this.authorRepository
.createQueryBuilder('a')
.select(['a.*', 'b.*', 'c.*'])
.leftJoin('a.books', 'b')
.leftJoin('b.bookMetadata', 'c')
.where('a.key = ?', [key])
.andWhere('c.localeKey = ?', [localeKey])
.getSingleResult();
}
}
Am I missing something? Might be not related, but I also noticed that there is a special autoLoadEntities: true for TypeORM users using Nest.js. Is there something similar for Mikro-ORM? Thanks ;)
Mapping of multiple entities from single query is not yet supported, it is planned for v4. You can subscribe here: https://github.com/mikro-orm/mikro-orm/issues/440
In v3 you need to use 2 queries to load 2 entities, which for your use case is much easier without the QB involved.
return this.authorRepository.findOne({ key }, ['books']);
Or you could use qb.execute() to get the raw results and map them yourself, but you would also have to manually alias all the fields to get around duplicities (Author.name vs Book.name), as doing qb.select(['a.*', 'b.*']) will result in query select a.*, b.* ... and the duplicate columns would not be correctly mapped.
https://mikro-orm.io/docs/query-builder/#mapping-raw-results-to-entities
About the autoLoadEntities thing, never heard of that, will take a look how it works, but in general, the nestjs adapter is not developed by me, so if its something only nest related, it would be better to ask on their GH repo.
Or you could use folder based discovery (entitiesDirs).
here is the new example with 3 entities:
return this.authorRepository.findOne({
key,
books: { bookMetadata: localeKey } },
}, ['books.bookMetadata']);
This will produce 3 queries, one for each db table, but the first one will auto-join books and bookMetadata to be able to filter by them. The condition will be propagated down in the second and third query.
If you omit the populate parameter (['books.bookMetadata']), then only the first query will be fired and you will end up with books not being populated (but the Author will be queried with the joined condition).

Avoid Type '{}' is not assignable to type 'X'

I'm migrating JavaScript project to TypeScript.
Using a node module in TS such as URL is causing some trouble for me:
import nodeUrl = require('url');
// ...
// this worked fine in JS
nodeUrl.format({
// just for demonstration
x: this.getX(someObj),
y: this.getY(someObj)
});
Results in:
Type '{}' is not assignable to type 'string'
This is due to the definition of that module function. From #types/node/index.d.ts:
declare module "url" {
export interface Url {
href?: string;
protocol?: string;
auth?: string;
hostname?: string;
port?: string;
host?: string;
pathname?: string;
search?: string;
query?: string | any;
slashes?: boolean;
hash?: string;
path?: string;
}
export function parse(urlStr: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url;
export function format(url: Url): string;
export function resolve(from: string, to: string): string;
}
My question is how do you avoid/fix this error without changing the declaration file?
Should be something like:
import nodeUrl = require('url');
declare module "url" {
export function format(url: Url): string;
export function format(x: any, y: any): string;
export function format(url: any): string;
}
More info about this can be found in Module Augmentation.
You could use an index signature:
export function format(url: {[index: string]: string}): string
This will make it so that format still requires an object with string keys and values, but the key names can be anything. Of course, you can mix and match the types to fit your needs.
Found another way to fix it:
nodeUrl.format(<any> {
// just for demonstration
x: this.getX(someObj),
y: this.getY(someObj)
});

Resources