How do I change the alias of a column in Typeorm? - sql

I want to change the name of a field with my QueryBuilder in the response body i.e a field called id, I want it to output as staff_id, I am having difficulties with that.
import { getRepository, Like } from 'typeorm';
import { RoomEntity } from '#entity/room.entity';
import { HttpException } from '#exceptions/HttpException';
import { isEmpty } from '#utils/util';
import { Room } from '#/interfaces/room.interface';
class RoomService {
public room = RoomEntity;
public async findQueryRoom(): Promise<Room[]> {
const rooms = await getRepository(this.room)
.createQueryBuilder('room')
.select(['room.id as staff_id', 'room.name'])
.getMany();
return rooms;
}
}
export default RoomService;
In the controller, I have:
import { NextFunction, Request, Response } from 'express';
import { Room } from '#interfaces/room.interface';
import RoomService from '#services/room.service';
class RoomsController {
public roomService = new RoomService();
public getRoomsByQuery = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
try {
const findAllRoomsData: Room[] = await this.roomService.findQueryRoom();
res.status(200).json({ data: findAllRoomsData, message: 'found all' });
} catch (error) {
next(error);
}
};
}
export default RoomsController;
The response I have in my postman does not include the staff_id field, I see
"data": [
{
"name": "Soba"
}
]
How can I solve this problem?

I don't know if you have gotten the solution already, but for those that are facing the same problem using select column alias with TypeORM. I face the same problem some time ago and below was my solution I don't know if it's a convincing solution but it solve my problem.
public async findQueryRoom(): Promise<Room[]> {
const rooms = await getRepository(this.room)
.createQueryBuilder('room')
.select(['room.id AS staff_id', 'room.name AS name'])
.groupBy("room.id")
.getRawMany();
return rooms;
}
Why .groupBy("room.id") when .groupBy("room.id") was absent it keep on selecting each row as many as the total row for example if there are 5 rows in total it will return each row 5 times that is why I introduced .groupBy("room.id") to rid of that.
For 'room.name AS name' if you leave 'room.name' it will return room_name instead of name.

Related

How to use graphql dataloader loadMany function properly in nestjs?

I want to use dataloader loadMany function in nestjs. Can any help me to use it properly-
dataloader.service.ts-
#Injectable()
export class DataloaderService {
constructor(private readonly categoryService: CategoryService) { }
createLoaders(): IDataloaders {
const subCategoryLoader = new DataLoader<ObjectId, Subcategory>(
async (keys: readonly ObjectId[]) =>
this.categoryService.findSubCategoryByBatch(keys as ObjectId[])
);
return {
subCategoryLoader
};
}
}
Then I category service(findSubCategoryByBatch)-
async findSubCategoryByBatch(Ids: ObjectId[]): Promise<(Subcategory | Error)[]> {
const categories = await this.subCategoryModel.find({ _id: { $in: Ids } });
const mappedResults = Ids.map(
(id) =>
categories.find((result) => result.id === id) ||
new Error(`Could not load owner ${id}`),
);
return mappedResults;
}
Then I call it -
#ResolveField('subCategory', () => [Subcategory])
getSubCategory(
#Parent() category: Category,
#Context() { loaders }: IGraphQLContext
) {
return loaders.subCategoryLoader.loadMany(category.subCategory)
}
Notice: I use loadMany function because subCategory is a array IDs.
But I am getting error. Here How to write function for loadMany function. Please help me. I need it. Please help me. please help me.

Fetch GraphQL data based on variable

I am trying to get my query to react to a ref property.
https://v4.apollo.vuejs.org/guide-composable/query.html#variables
This wont work at all
const { result, variables } = useQuery(gql`
query {
episodes(page: $page) {
info {
pages
count
}
results {
name
}
}
}
`, {
page: 2
});
Tried this as well
setup() {
const currentPage = ref(1);
const { result } = useQuery(gql`
query {
episodes(page: ${currentPage.value}) {
info {
pages
count
}
results {
name
}
}
}
`);
function pageChange() {
currentPage.value += 1;
console.log(currentPage.value)
}
return { result, currentPage, pageChange };
},
This code below works for me when I input page number manually, but I want to pass the page number as variable, because my pagination page increases and I want the query to refresh.
const { result, loading } = useQuery(gql`
query {
episodes(page: 2) {
info {
pages
count
}
results {
name
}
}
}
`,
);
Can someone assist me?
In the link you gave query is followed by the query name.
const { result } = useQuery(gql`
query getUserById ($id: ID!) {
user (id: $id) {
id
email
}
}
`, {
id: 'abc-abc-abc',
})
You don’t specify the query name
Try this instead:
const { result, variables } = useQuery(gql`
query episodes($page: Int) {
episodes(page: $page) {
info {
pages
count
}
results {
name
}
}
}
`, {
page: 2
});
I don’t know what’s your schema looks like but I inferred that page is a Int. If it’s not change Int by the page type

How to sort result set using computed fields (type-graphql)

I'm using type-graphql and typeorm. Is there a way to sort the result based on a computed field. Specifically, I want to return a list of Clients and sort the list based on a computed field: "sortName". Sort name is simply a string of the clent's "firstName lastName" or "lastName FirstName". The decision on how to generate the sortName is based on a flag in the Company table (that way the user can control how they want to view their clients). I just don't know how to do the sort prior to sending back to the front-end app. I know I can create a view and do it in sql - but I'd like to know if it's possible to do in code.
import {Arg, Ctx, Field, FieldResolver, ID, InputType, ObjectType, Query, Resolver, Root,} from 'type-graphql'
import {Client} from '../entities/Client'
import {ClientNameSort, Company} from '../entities/Company'
import {MyContext} from '../types/MyContext'
#InputType()
export class ClientsOptions {
#Field(() => ID)
companyId!: string
}
#ObjectType()
#Resolver(Client)
export class ClientResolver {
#FieldResolver(() => String)
async sortName(#Root() client: Client, #Ctx() { companyLoader }: MyContext) {
const company:Company = await companyLoader.load(client.companyId)
if (!company) {
throw new Error(`Missing rec for Company Id ${client.companyId}`)
}
if (company.clientNameSort === ClientNameSort.FIRST_NAME) {
return `${client.firstName} ${client.lastName} ${client.id}`
} else {
return `${client.lastName} ${client.firstName} ${client.id}`
}
}
#Query(() => [Client])
async clients(#Arg('options') options: ClientsOptions) {
const clientList = await Client.find({ where: { companyId: options.companyId } })
return clientList;
}
}
I believe you have to do the sorting on the "clients" method. Therefore i am not sure the field resolver is going to help you. You better separate that into a utility function and reuse it in both methods.
To to the sorting on the clients method:
if you use mongodb, maybe you can do an aggregated query that will create this virtual field and order by it
if you use another DB , you will have to look if they have this kind of feature
If you don't want to do sorting through DB, you can get the array of clients and do a sort
clients.sort((a,b) => sortByCompanyName(company.CLIENT_NAME_SORT, a, b))
getFullIdentificator(order, client) {
if (order === ClientNameSort.FIRST_NAME) {
return `${client.firstName} ${client.lastName} ${client.id}`
} else {
return `${client.lastName} ${client.firstName} ${client.id}`
}
}
sortByCompanyName(order, prev, next) {
return getFullIdentificator(order, prev) > getFullIdentificator(order, next) ? 1 : -1
}

Angular 5 - Event emitter (Property 'update' does not exist on type ....)

I've got a component that I want to update when a person's name changes by emitting an event. My problem is the code doesn't compile because of an error. This is my code
ApplicationFormComponent
#Output() nameChange = new EventEmitter();
closeAccordion(isComplete: string, accordionToClose: string, accordion: NgbAccordion) {
if (accordionToClose === 'personal-details-panel') {
this.applicationStatusFlags.personalDetailsStatus = (isComplete === 'true');
this.nameChange.emit({ personId: this.personId });
}
}
ApplicationFormComponent.html
<name-display
[personId]="personId"
[placeHolderText]="'Hello'"
(nameChange)="update($event)">
</name-display>
NameDisplayComponent
import { Component, Input, OnChanges, SimpleChanges } from '#angular/core';
import { PersonService } from "../../../service/person.service";
#Component({
selector: 'name-display',
templateUrl: './NameDisplay.component.html',
providers: [PersonService]
})
export class NameDisplayComponent implements OnChanges {
constructor(private readonly personService: PersonService) { }
#Input() personId;
#Input() placeHolderText: string = "";
forename: string = "";
ngOnChanges(changes: SimpleChanges): void {
if (changes["personId"]) {
this.personService.getPersonDetails(this.personId).subscribe((res: IPersonDetails) => {
this.forename = res.forenames;
});
}
};
update(personId: number) {
alert("update name");
this.personService.getPersonDetails(personId).subscribe((res: IPersonDetails) => {
this.forename = res.forenames;
});
}
}
My problem is basically when I use angular cli with the command ng server --aot, it doesn't compile because of this error:
ERROR in src\app\component\ApplicationForm\ApplicationForm.component.html(42,9): : Property 'update' does not exist on type 'ApplicationFormComponent'.
I've written a similar component that uses an event emitter which doesn't have this problem, so I'm stuck with how to fix the error.
Any ideas?
It is because you are passing $event to method.
(nameChange)="update($event)"
But it accepts number.
update(personId: number) {
alert("update name");
}
Please change the method as below.
update(event:any) {
const personId = event as number
alert("update name");
}

ngx-chart error "TypeError: Object(...) is not a function"

I am trying to implements some statistics in my develepping platform and I try to use ngx-charts to display them. However I get an error and I can't figure out why.
I am using storedProcedures for MySQL statistics which I call from Java Restful Backend and return them in Angular 5 front-end. The returned table has the following two fields: Date and number of incidents per day. So the table returned by the backend has those two columns.
My code for the component rendering the chart is the following:
import {Component, OnInit} from '#angular/core';
import {StatisticsService} from '../../statistics.service';
class Data {
private _name: string;
private _value: number;
get name(): string {
return this._name;
}
set name(value: string) {
this._name = value;
}
get value(): number {
return this._value;
}
set value(value: number) {
this._value = value;
}
}
#Component({
selector: 'app-daily-incidents-statistics',
templateUrl: './daily-incidents-statistics.component.html',
styleUrls: ['./daily-incidents-statistics.component.css']
})
export class DailyIncidentsStatisticsComponent implements OnInit {
view: any[] = [700, 400];
data: any[] = [];
// options
showXAxis = true;
showYAxis = true;
gradient = false;
showLegend = false;
showXAxisLabel = true;
xAxisLabel = 'Ημέρα';
showYAxisLabel = true;
yAxisLabel = 'Αρ. Περιστατικών';
constructor(private statisticsService: StatisticsService) {
// Object.assign(this, { single })
// Object.assign(this, { data } );
}
colorScheme = {
domain: ['#5AA454', '#A10A28', '#C7B42C', '#AAAAAA']
};
onSelect(event) {
console.log(event);
}
async ngOnInit() {
console.log('NG ON INIT EXECUTION');
await this.getIncidentsByDay();
}
getIncidentsByDay() {
this.statisticsService.getIncidentsByDay()
.subscribe(
(results) => {
let temp = new Data();
for (let i in results) {
console.log(results[i][0] + '>>=====>> ' + results[i][1]);
temp.name = results[i][0];
temp.value = results[i][1];
this.data.push(temp);
}
const test = this.data;
// for (let i = 0; i < this.data.length; i++) {
// console.log('wtf: ' + this.data[i][0] + '::::' + this.data[i][1]);
// }
// console.log(results);
// console.log(JSON.stringify(results));
// Object.assign(this, {test});
}
);
}
}
However when I run the above code I get in JavaScript console the error:
ERROR TypeError: Object(...) is not a function
at BarVerticalComponent../src/common/base-chart.component.ts.BaseChartComponent.bindWindowResizeEvent (index.js:7818)
at BarVerticalComponent../src/common/base-chart.component.ts.BaseChartComponent.ngAfterViewInit (index.js:7730)
at callProviderLifecycles (core.js:12689)
at callElementProvidersLifecycles (core.js:12656)
at callLifecycleHooksChildrenFirst (core.js:12639)
at checkAndUpdateView (core.js:13794)
at callViewAction (core.js:14136)
at execComponentViewsAction (core.js:14068)
at checkAndUpdateView (core.js:13791)
at callViewAction (core.js:14136)
My Html Template File:
<div>
lalalal <br/>
ante pali... <br/>
kala ti na pw... <br/>
Gamiete pali... <br/>
<ngx-charts-bar-vertical
[view]="view"
[scheme]="colorScheme"
[results]="data"
[gradient]="gradient"
[xAxis]="showXAxis"
[yAxis]="showYAxis"
[legend]="showLegend"
[showXAxisLabel]="showXAxisLabel"
[showYAxisLabel]="showYAxisLabel"
[xAxisLabel]="xAxisLabel"
[yAxisLabel]="yAxisLabel"
(select)="onSelect($event)">
</ngx-charts-bar-vertical>
</div>
While the service for retreiving the values is:
import {Injectable} from '#angular/core';
import {HttpClient} from '#angular/common/http';
import {catchError} from 'rxjs/operators';
import {ErrorHandler} from '../shared/lib/error-handler';
import {Observable} from 'rxjs/Observable';
#Injectable()
export class StatisticsService {
constructor(private http: HttpClient) {
}
public getIncidentsByDay(): Observable<any> {
console.log("FEtching Incidents All By Day");
const url = 'statistics/incidents/day';
return this.http.get(url)
.pipe(catchError(ErrorHandler.handleError));
}
}
What am I doing wrong?
I am using Angular version 5.3 and ngx-charts 8.0 which is compatible with Angular 6 and not Angular 5. I installed ngx-charts version 7.4 and everything works fine.
I fixed the problem for me by downgrading to version 7.3.0
yarn add #swimlane/ngx-charts#7.3.0
I think I see the same with ngx-charts-bar-horizontal, whereas before this was not the case. The documentation page seems to be broken at the moment as well, so I assume the software has recently been updated in a broken way.
If you really need to use the 8.0 version, you can upgrade to angular 6 to solve the problem. Here is how you can do the upgrade from v5 to v6 https://stackoverflow.com/a/49474334
You can also think that the documention page is broken by now but ou can find it here https://swimlane.gitbook.io/ngx-charts/v/docs-test/installing