I'm trying to make many request in nestJs and specially some with the role of my users and i wanted to be able to list all users who match user.role = "Role's name" but i can't get the foreign key user from my table role.
My controller look like this and both of my entities reference each other as a role can have one or many user and a user one and only one role.
import { Controller, Get, Param, Post } from '#nestjs/common';
import { Body } from '#nestjs/common/decorators';
import { AuthDto } from 'src/authentification/auth.dto';
import { Role } from './role.entity';
import { User } from './user.entity';
import { UserService } from './user.service';
#Controller('user')
export class UserController {
constructor(private readonly UserService: UserService){}
#Get()
async getAllUser(): Promise<User[]>{
return this.UserService.getListUser();
}
#Get('/Role')
async getListRole(): Promise<Role[]> {
return this.UserService.getListRole();
}
#Get('/Role/:role')
async getUserByRole(#Param('role') role : number): Promise<User[]> {
return this.UserService.getUserByRole(+role);
}
#Get('/Pseudo/:pseudo')
async getUserByPseudo(#Param('pseudo') pseudo : string): Promise<User> {
return this.UserService.getUserByPseudo(pseudo);
}
#Get('/id/:id')
async getUserById(#Param('id') id : number): Promise<User> {
return this.UserService.getUserById(+id);
}
#Post('/New')
async createUser(#Body() user: AuthDto){
return this.UserService.createUser(user);
}
}
and here is the service
import { Get, Injectable } from '#nestjs/common';
import { InjectRepository } from '#nestjs/typeorm';
import { AuthDto } from 'src/authentification/auth.dto';
import { Repository } from 'typeorm';
import { Role } from './role.entity';
import { User } from './user.entity';
#Injectable()
export class UserService {
constructor(
#InjectRepository(User) private usersRepository: Repository<User>,
#InjectRepository(Role) private rolesRepository: Repository<Role>
){}
getUserById(id): Promise<User> {
return this.usersRepository.findOneOrFail(id);
}
getUserByPseudo(pseudo: string): Promise<User> {
return this.usersRepository.findOne({pseudo});
}
getListRole(): Promise<Role[]> {
return this.rolesRepository.find();
}
getListUser(): Promise<User[]> {
return this.usersRepository.find();
}
getUserByRole(role): Promise<User[]> {
return this.usersRepository.find({where: {role: role}});
}
createUser(data: AuthDto){
const user = {
pseudo: data.username,
password: data.password,
pointEffort: 10,
scienceTab: [],
inventaire: [],
technologieTab: [],
role: {
id: 1,
nom: "joueur",
users: []
},
};
const result = this.usersRepository.save(user);
return result;
}
}
user.entity.ts
import { Place } from "src/place/place.entity";
import { Science } from "src/science/science.entity";
import { TechnologieUser } from "src/technologie/technologieUser.entity";
import { Column, Entity, ManyToMany, ManyToOne, OneToMany, PrimaryGeneratedColumn } from "typeorm";
import { Role } from "./role.entity";
#Entity()
export class User {
#PrimaryGeneratedColumn()
id: Number;
#Column()
pseudo: String;
#Column()
password: String;
#Column()
pointEffort: Number;
#ManyToOne(type => Role, role => role.users)
role: Role;
#ManyToMany(type => Science, science => science.users)
scienceTab: Science[];
#OneToMany(type => TechnologieUser, technologieUser => technologieUser.user)
technologieTab: TechnologieUser[];
#OneToMany(type => Place, place => place.user)
inventaire: Place[];
}
role.entity.ts
import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from "typeorm";
import { User } from "./user.entity";
#Entity()
export class Role {
#PrimaryGeneratedColumn()
id: Number;
#Column()
nom: String;
#OneToMany(type => User, user => user.role)
users: User[];
}
But when i use getListRole() i only get this
And so i don't have the list of my users returned in the property role.users which is missing.
So the question is : how can i have role.users added in the data of getListRole()?
Thx a lot
Get role id from params, then do, this.usersRepository.find({ relations: {Role: true}, where: { role: { id: roleId } } })
Related
I have the following type script inside my ReactJs SPFx sharepoint online web part:-
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '#microsoft/sp-core-library';
import {
IPropertyPaneConfiguration,
IPropertyPaneDropdownOption,
PropertyPaneDropdown} from '#microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '#microsoft/sp-webpart-base';
import * as strings from 'ContactListWebPartStrings';
import ContactListApp from './components/ContactListApp';
import { IContactListProps } from './components/IContactListProps';
import { sp } from "#pnp/sp/presets/all";
export interface IContactListWebPartProps {
department: string;
}
export default class ContactListWebPart extends BaseClientSideWebPart<IContactListWebPartProps> {
private viewModeOptions: IPropertyPaneDropdownOption[] = null;
public render(): void {
const element: React.ReactElement<IContactListProps> = React.createElement(
ContactListApp,
{
department: this.properties.department,
context: this.context
}
);
ReactDom.render(element, this.domElement);
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
public onInit(): Promise<void> {
return super.onInit().then( _ => {
sp.setup({
spfxContext: this.context
});
const choice =
sp.web.lists.getByTitle('Contacts').fields.getByTitle('Department').get();
this.viewModeOptions = choice.Choices.map((choice: string, idx: number) =>
{
return {
key: idx,
text: choice
}
})
});
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneDropdown('department', {
label: 'Department',
options: this.viewModeOptions,
selectedKey: this.viewModeOptions[0].key,
disabled: !this.viewModeOptions
}),
]
}
]
}
]
};
}
}
but i am getting this error on choice.Choices.map:-
Property 'Choices' does not exist on type 'Promise'
Change this:
const choice = sp.web.lists.getByTitle('Contacts').fields.getByTitle('Department').get();
(In this case choice is just Promise, not returned value.)
For this:
const choice = await sp.web.lists.getByTitle('Contacts').fields.getByTitle('Department').get();
(In this case await cause to load data and choice contains value.)
With await inside function, you need to make it async like this:
return super.onInit().then(async _ => {
I am getting the below JSON data from a rest web service. I am trying to figure out how I can convert to an array of object.
{
"John": "Buttler"
"Hugh": "Martin"
.
.
.
}
I am trying to convert to below object. Basically I am expecting Person[]. In above JSON, John, Hugh are first names and Buttler, Martin are last names.
export class Person{
firstName: string;
lastName: string;
}
I am able to convert if I get the json as below
[
{
"firstName": "John"
"lastName:: "Buttler"
},
{
"firstName": "Hugh"
"lastName:: "Martin"
}
]
Angular Service Code:
findAllPersons(): Observable<Person[]> {
return this.httpClient.get<Person[]>('url');
}
You have to process the recieved response in your required format.
findAllPersons(): Observable<Person[]> {
return this.httpClient.get<object>('url');
}
findAllPersons().subscribe((response) =>{
let array = [];
for(let key in response){
let p = new Person();
p.firstName = key;
p.lastName = response[key];
array.push(p);
}
console.log(array); // your required array
});
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
interface NameData {
[firstName: string]: string;
}
interface Person {
firstName: string;
lastName: string;
}
#Injectable()
class PersonService {
constructor(private httpClient: HttpClient) {}
findAllPersons(): Observable<Person[]> {
return this.httpClient.get<NameData>('url').pipe(
map((v) =>
Object.entries(v).map(([firstName, lastName]) => ({
firstName,
lastName,
}))
)
);
}
}
React-Router receive code
import React from "react";
import { Mutation } from "react-apollo";
import { RouteComponentProps } from "react-router-dom";
import { toast } from "react-toastify";
import { LOG_USER_IN } from "../../sharedQueries.local";
import { verifyPhone, verifyPhoneVariables } from "../../types/api";
import VerifyPhonePresenter from "./VerifyPhonePresenter";
import { VERIFY_PHONE } from "./VerifyPhoneQueries";
interface IState {
verificationKey: string;
phoneNumber:string;
}
interface IProps extends RouteComponentProps<any> {}
class VerifyMutation extends Mutation<verifyPhone,
verifyPhoneVariables> {}
class VerifyPhoneContainer extends React.Component<IProps, IState> {
constructor(props: IProps) {
super(props);
if (!props.location.state) {
props.history.push("/");
}
debugger;
this.state = {
phoneNumber: props.location.state.phone,
verificationKey: ""
};
}
React-Router send code
import React from "react";
import { Mutation, MutationFn } from "react-apollo";
import { RouteComponentProps } from "react-router-dom";
import { toast } from "react-toastify";
import {
startPhoneVerification,
startPhoneVerificationVariables
} from "../../types/api";
import PhoneLoginPresenter from "./PhoneLoginPresenter";
import { PHONE_SIGN_IN } from "./PhoneQueries";
interface IState {
countryCode: string;
phoneNumber: string;
}
class PhoneSignInMutation extends Mutation<
startPhoneVerification,
startPhoneVerificationVariables
> {}
class PhoneLoginContainer extends React.Component<
RouteComponentProps<any>,
IState
> {
public phoneMutation: MutationFn;
public state = {
countryCode: "+82",
phoneNumber: ""
};
public render() {
const { history } = this.props;
const { countryCode, phoneNumber } = this.state;
return (
<PhoneSignInMutation
mutation={PHONE_SIGN_IN}
variables={{
phoneNumber: `${countryCode}${phoneNumber}`
}}
onCompleted={data => {
const { StartPhoneVerification } = data;
const phone = `${countryCode}${phoneNumber}`;
if (StartPhoneVerification.ok) {
toast.success("SMS Sent! Redirecting you...");
setTimeout(() => {
history.push({
pathname: "/verify-phone",
state: {
phone
}
});
}, 2000);
} else {
toast.error(StartPhoneVerification.error);
}
}}
>
{(phoneMutation, { loading }) => {
this.phoneMutation = phoneMutation;
return (
<PhoneLoginPresenter
countryCode={countryCode}
phoneNumber={phoneNumber}
onInputChange={this.onInputChange}
onSubmit={this.onSubmit}
loading={loading}
/>
);
}}
</PhoneSignInMutation>
);
}
Failed to compile. Property 'phone' does not exist on type '{}'.
Please let me know why the error is occurring.
I'm going to make a text message and authentication with my cell phone.
However, the error below occurs while handing over the phone number to the next page from the previous page.
I am using a translator because my English is not good.
i solved
if (!props.location.state) {
props.history.push("/");
}
const {
location: { state }
} = props;
let phoneNumber = "";
if (state) {
phoneNumber = state.phone;
} else {
phoneNumber = "";
}
this.state = {
phoneNumber,
verificationKey: ""
};
Hello i want to pass the user id (uid) from the home page to a user Details Page. Because i display multiple users on my home page i don’t wan to pass the user session id (as given by the JSON.parse(localStorage.getItem("userData")); ), i want to click on the name of any user on the home page and pass its id and other parameters on the user details page.
home.html
<p (click)="UserPage()" [innerHTML]="item.username | linky"></p>
home.ts
public userDetails: any;
public resposeData: any;
public dataSet: any;
public noRecords: boolean;
rootPage: any = HomePage;
pages: Array<{ title: string, component: any }>;
userPostData = {
uid: “”,
token: “”,
username: “”,
message: “”,
msg_id: “”,
title: “”,
description: “”,
media_pic: “”,
created:""
};
constructor(
public common: Common,
public navCtrl: NavController,
public app: App,
public menu: MenuController,
public authService: AuthService,
platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen,
) {
const data = JSON.parse(localStorage.getItem("userData"));
this.userDetails = data.userData;
this.userPostData.uid = this.userDetails.uid;
this.userPostData.token = this.userDetails.token;
this.userPostData.username = this.userDetails.username;
this.userPostData.msg_id = this.userDetails.msg_id;
this.userPostData.message = this.userDetails.message;
this.userPostData.title = this.userDetails.title;
this.userPostData.description = this.userDetails.description;
this.userPostData.media_pic = this.userDetails.media_pic;
this.userPostData.created = this.userDetails.created;
this.noRecords = false
this.allArtists();
}
note: this is how i call the users via Auth Service
allArtists() {
this.common.presentLoading();
this.authService.postData(this.userPostData, “newsFeed”).then(
result => {
this.resposeData = result;
if (this.resposeData.friendsNewsFeed) {
this.common.closeLoading();
this.dataSet = this.resposeData.friendsNewsFeed;
console.log(this.dataSet);
} else {
console.log("No access");
}
},
err => {
//Connection failed message
}
);
}
UserPage() {
this.navCtrl.push(UserPage, { uid: this.userPostData.uid });
userProfile.ts
mport { NavController, App, AlertController, MenuController, NavParams } from “ionic-angular”;
export class UserPage {
public uid: string;
constructor(
public common: Common,
public navCtrl: NavController,
public app: App,
public menuCtrl: MenuController,
public navParams: NavParams,
public authService: AuthService
) {
this.uid = navParams.get(‘uid’);
console.log(this.uid);
this.userProfile();
}
}
auth-service.ts
import { Injectable } from '#angular/core';
import { Http, Headers } from '#angular/http';
import 'rxjs/add/operator/map';
let apiUrl = "http://localhost/PHP-Slim-Restful1/api/";
//let apiUrl = 'https://api.thewallscript.com/restful/';
/*
Generated class for the AuthService provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
#Injectable()
export class AuthService {
constructor(public http: Http) {
console.log('Hello AuthService Provider');
}
postData(credentials, type){
return new Promise((resolve, reject) =>{
let headers = new Headers();
this.http.post(apiUrl+type, JSON.stringify(credentials), {headers: headers}).
subscribe(res =>{
resolve(res.json());
}, (err) =>{
reject(err);
});
});
}
}
With NavParams, you doing it the right way already.
It is not visible for me how your item structure is. When you setup your links at your homepage like this: <p (click)="UserPage()" [innerHTML]="item.username | linky"></p>, you could pass the user id of this item into the function like this: UserPage(user.uid).
What happens now, is that your UserPage function already gets the right uid and can pass it to the detailed view.
OK I got the answer. You need to pass the parameters in the with onclick.
home.html
home.ts
UserPage(uid_fk) {
this.navCtrl.push(UserPage, { uid_fk: uid_fk });
console.log(uid_fk);
}
I need to modify my code where loading detail category will first look whether it is not already loaded in the statement, and if not then detail loads. Thanks for help!
Constructor of CategoryProvider:
private _obServers = {
'categoryList': undefined,
'category': undefined,
'idCategory': new Subject<Number>()
};
constructor(){
this.categories = new Observable(observer => this._obServers.categoryList = observer).share();
this._categoryObservable = this.categories
.combineLatest(this._obServers.idCategory, (categories, idCategory) => {
return categories.filter(category => category.id === idCategory)[0];
})
.distinctUntilChanged((oldCategory, newCategory) => {
return oldCategory.id === newCategory.id;
});
}
CategoryList:
loadCategories(search?:string):void{
this._http
.get('/services/category/list?search=' + search)
.map(res => res.json())
.subscribe(data => {
this._obServers.categoryList.next(this.createCategoryEntities(data));
});
}
CategoryDetail:
loadCategory(categoryId:number){
this._obServers.idCategory.next(categoryId);
//If category not loaded I need to load it
}
I have followed this way https://github.com/JonatanSCS/Angular-2-Tutorial/blob/master/node_modules/rxjs/src/add/observable/combineLatest.ts
import { Component, Injectable, Inject, provide } from '#angular/core';
import { HTTP_PROVIDERS } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import { combineLatestStatic } from 'rxjs/operator/combineLatest.js';
import { MessageApi } from '../providers/lb-service/lb-services.provider'
import { EstimatesService } from './estimates.service';
#Component({
pipes: [TranslatePipe],
})
#Injectable()
export class InvoiceService {
constructor(private _message:MessageApi,
#Inject(EstimatesService) _estimates:EstimatesService) {
this._message = _message;
this._estimates = _estimates;
Observable.combineLatest = combineLatestStatic;
declare module 'rxjs/Observable' {
namespace Observable {
export let combineLatest: typeof combineLatestStatic;
}
}
Observable.combineLatest(
this._estimates.getEstimates(),
this._message.findOne({
where: {
moduleTag: 'monthlyStat',
'dynamic.date': "2016-07-01" //new Date
},
fields: {
dynamic: true
}
}),this._message.findOne({
where: {
moduleTag: 'areaPriceSE1',
'dynamic.date': ''
},
fields: {
dynamic: true
}
})
).subscribe(res => console.log("observable", res));