How to get table content of database in NestJS? - mysql

I created a database in MySQL with the name: refy. It contains one table called app.
Using NestJS, I am trying to find all columns in the table like this:
import { Controller, Get } from '#nestjs/common';
import { AppService } from './app.service';
import { App } from 'src/database/refy/app.entity';
#Controller()
export class AppController {
constructor(private readonly refyService: AppService) {}
#Get('/refy')
findAll(): Promise<App[]> {
return this.refyService.findAll();
}
}
Entity file has:
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
#Entity({name: 'app'})
export class App {
#PrimaryGeneratedColumn()
id: number;
#Column()
name: string;
#Column()
webhookSecretKey: string;
#Column()
webhookUrl: string;
#Column()
clientId: string;
#Column()
clientSecretKey: string;
}
Apparently, the database is well connected and reached;
however, when I use Postman to get the data it gives a 500 error:
With terminal debug error:
EntityMetadataNotFoundError: No metadata for "App" was found
I want it to return data like this:
{
"webhookSecretKey": "1",
"webhookUrl": "2",
"clientId": "3",
"clientSecretKey": "4",
"id": 5,
"name": "6"
}

This can happen for two main reasons :
You have the wrong path in your OrmConfig, update it like this :
entities: [__dirname + '/../**/*.entity.{js,ts}']
You forgot to add the entity App to the TypeOrmModule.forRoot inside the imports array to the main module :
imports: [
TypeOrmModule.forRoot({
entities: [App]
}),
],

Related

How to delete table created by manytomany relationship in typeorm by changing entity

I previously add a many to many relation with my User and Project entity
User
import { Entity, Column, OneToMany, ManyToMany } from "typeorm";
import { BaseUuidEntity } from "../utils/entity/baseUuidEntity";
import { Project } from "./project";
#Entity()
export class User extends BaseUuidEntity {
#Column("varchar", { nullable: false, length: 40 })
Name!: string;
#Column("varchar", { nullable: false, length: 40 })
Email!: string;
#ManyToMany((type) => Project, (Project) => Project.Id)
Projects: Project[];
}
Project.ts
import { Entity, Column, OneToMany, ManyToMany, JoinTable } from "typeorm";
import { BaseUuidEntity } from "../utils/entity/baseUuidEntity";
import { Bug } from "./bug";
import { User } from "./user";
#Entity()
export class Project extends BaseUuidEntity {
#Column("varchar", { nullable: false, length: 32 })
ProjectName!: string;
#Column({ type: "bool" })
IsArchived: boolean;
#Column("boolean")
IsPrivate: boolean;
#ManyToMany((type) => User)
#JoinTable({
name: "ProjectMember", // table name for the junction table of this relation
joinColumn: {
name: "user",
referencedColumnName: "Id",
},
inverseJoinColumn: {
name: "project",
referencedColumnName: "Id",
},
})
Members: User[];
#OneToMany((type) => Bug, (Bug) => Bug.Id)
Bugs: Bug[];
}
But Now I have removed the many to many relation from both entity and created a new Entity Project member
But when I ran the migration script it didn't delete the JoinTable created by many to Many relation, how can I delete it?

Nested objects deserialization to a TypeScript Class

I have a class, for example, let's say a Car with the below structure.
#Serializable()
export default class Car {
#JsonProperty({
name: 'id'
})
private id!: string;
#JsonProperty({
name: 'name'
})
private name!: string;
#JsonProperty({
name: 'carOwner'
})
private carOwner!: Owner;
}
Further I have the Owner class.
#Serializable()
export default class Owner{
#JsonProperty({
name: 'id'
})
private id!: string;
#JsonProperty({
name: 'name'
})
private name!: string;
#JsonProperty({
name: 'address'
})
private address!: string;
}
I have an incoming JSON Object with below structure, let's call it newCar
{
"id": "test-id",
"name": "test-car",
"carOwner": {
"id": "owner-id",
"name": "owner-name",
"address": "owner-address",
"gender": "owner-gender",
"age": "owner-age",
}
}
What I want to do is, deserialize the newCar JSON to the Car class. That is when I deserialize newJson I should get the below object, where gender and age are filtered out.
{
"id": "test-id",
"name": "test-car",
"carOwner": {
"id": "owner-id",
"name": "owner-name",
"address": "owner-address"
}
}
But right now what I am getting is the original newJson. It seems that the library (typescript-json-serializer) which I am using does not deserialize nested objects, here which is owner.
Any input will be appreciated.
Here is the link to the package typescript-json-serializer
Found the solution for it. Apparently I missed to add one parameter in JsonProperty().
In the Car class, for carOwner object, I had to pass type of owner.
#JsonProperty({
name: 'carOwner',
type: Owner,
})
The above solved the issue I was facing.

How to create TypeScript class from Json data? [duplicate]

This question already has answers here:
How do I cast a JSON Object to a TypeScript class?
(28 answers)
How to parse a JSON object to a TypeScript Object
(11 answers)
How do I initialize a TypeScript Object with a JSON-Object?
(18 answers)
Closed 1 year ago.
I'm using Angular to call an external API. Json data is in format like:
[
{
"AccessGroupsIdList": [],
"FirstName": "Greg",
"LastName": "Tipton",
"LocationIdList": [],
"PermissionProfile": {
"Name": "Agent",
"PermissionProfileId": {
"ID": "xy678219-bd7c-103d-b56b-1f1234a85990"
},
"Type": 3
},
"ManagerName": "Gilchrist, George",
"Status": true,
"UserGroupID": {
"ID": "00000000-0000-0000-0000-000000000000"
},
"UserGroupName": "ROOT",
"UserId": {
"ID": "4445cc66-819a-4da0-8fbf-d0bb8ce65941"
}
}
]
How do I create a class in typescript to read it since json data is nested?
export class Employees
{
AccessGroupsIdList: string[];
FirstName: string;
LastName: string;
LocationIdList : number[];
PermissionProfile ??
ManagerName: string;
Status: boolean;
UserGroupID ??
UserGroupName : string;
UserId ??
}
Please guide if the PermissionProfile, PermissionProfile will be separate nested classes?
How do I declare those?
To extend Andrew Halil's answer, I would use interfaces instead of classes in your definitions, since there do not appear to be any class methods involved; you are just describing the shape of a JSON object returned from a server
export interface Employee
{
AccessGroupsIdList: string[];
FirstName: string;
LastName: string;
LocationIdList : number[];
PermissionProfile: PermissionProfile;
ManagerName: string;
Status: boolean;
UserGroupId: ID;
UserGroupName : string;
UserId: ID;
}
export interface PermissionProfile
{
name: string;
permissionProfileId: ID;
type: string;
}
export interface ID
{
id: string;
}
Now as for an implementation, I don't use Angular all that much but you would do something like this to get the items typed
async function listEmployees(): Promise<Employee[]> {
// Make a fetch call to the API endpoint
const data = await fetch('https://some-api-endpoint.web/employees')
// if the response comes back ok, return the JSON-ified response.
.then(res => {
if(res.ok) return res.json()
return [];
});
// Instruct typescript that "data" is to be treated as an array of Employee elements.
return data as Employee[]
}
Try declaring the Typescript class structures as follows:
export class Employees
{
AccessGroupsIdList: string[];
FirstName: string;
LastName: string;
LocationIdList : number[];
PermissionProfile: PermissionProfile;
ManagerName: string;
Status: boolean;
UserGroupId: UserGroupID;
UserGroupName : string;
UserId: UserID;
}
export class PermissionProfile
{
name: string;
permissionProfileId: PermissionProfileID;
type: string;
}
export class PermissionProfileID
{
id: string;
}
export class UserGroupID
{
id: string;
}
export class UserID
{
id: string;
}
I would suggest to name the property names consistently with an Id (e.g. with UserGroupId). The name and type class property names are valid in TypeScript (unlike with the C# syntax).

Creating a model for a json

I'm trying to build a Azure cognitive text translator app in angular. Initially I need to load the supported languages. But when I use this link https://api.cognitive.microsofttranslator.com/languages?api-version=3.0. I'm getting response like this
"translation": {
"af": {
"name": "Afrikaans",
"nativeName": "Afrikaans",
"dir": "ltr"
},
"ar": {
"name": "Arabic",
"nativeName": "العربية",
"dir": "rtl"
},
"bg": {
"name": "Bulgarian",
"nativeName": "Български",
"dir": "ltr"
},
...
}
How to create a model that holds this type of json?
When I tried json2ts.com for building the model, it creates object for each language like
export interface Af {
name: string;
nativeName: string;
dir: string;
}
export interface Ar {
name: string;
nativeName: string;
dir: string;
}
export interface Bg {
name: string;
nativeName: string;
dir: string;
}
export interface Translation {
af: Af;
ar: Ar;
bg: Bg;
}
Do I need to create interface for all the available languages?
are there any other simple way to handle this?
The translation property of that object is a key-value map.
You could model the whole thing as follows:
type Dir = "ltr" | "rtl";
interface Translation {
name:string;
nativeName:string;
dir: Dir;
}
interface LangResponse {
translation: {[langCode:string]: Translation};
}
You could define a Typescript interface modeling the JSON data.
export interface LanguageInfo {
name: string
nativeName: string
dir: string
code?: string
toScripts?: Array<LanguageInfo>
}
export interface TranslationLanguages {
langCode: string
info: LanguageInfo
}
function fromJSON(json_data: string | Object): TranslationLanguages {
let obj: TranslationLanguages;
if (typeof json_data === "object") {
obj = json_data as TranslationLanguages;
} else {
obj = JSON.parse(json_data);
}
return obj;
}

how to parse json to angular 7 object?

I am trying to consume a web API that returns the following data
{
"FileStatuses": {
"FileStatus": [
{
"accessTime": 0,
"blockSize": 0,
"childrenNum": 13,
"fileId": 16396,
"group": "supergroup",
"length": 0,
"modificationTime": 1553247533630,
"owner": "hduser",
"pathSuffix": "demo-data",
"permission": "755",
"replication": 0,
"storagePolicy": 0,
"type": "DIRECTORY"
},
{
"accessTime": 0,
"blockSize": 0,
"childrenNum": 7,
"fileId": 16410,
"group": "supergroup",
"length": 0,
"modificationTime": 1550659883380,
"owner": "hduser",
"pathSuffix": "instacart",
"permission": "755",
"replication": 0,
"storagePolicy": 0,
"type": "DIRECTORY"
}
]
}
}
I created a service like this and the class to parse the json response to it:
public getHadoopDirList(): Observable<FileStatus[]> {
return this.http.get<FileStatus[]>(this.webHdfsUrl, {}).pipe(map(data => data));
}
export class FileStatus {
accessTime: number;
blockSize: number;
childNum: number;
fileId: number;
group: string;
length: number;
modificationTime: number;
owner: string;
pathSuffix: string;
permission: string;
replication: number;
storagePolicy: number;
type: string;
}
i subscribed to it on the component but when i try to iterate over it on the template i get the following ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed
I think the problem is the way how to map it but I didn't know how to solve it
use http://json2ts.com/ to convert JSON to interface
Your inteface should be like below
export interface FileStatus {
accessTime: number;
blockSize: number;
childrenNum: number;
fileId: number;
group: string;
length: number;
modificationTime: any;
owner: string;
pathSuffix: string;
permission: string;
replication: number;
storagePolicy: number;
type: string;
}
export interface FileStatuses {
FileStatus: FileStatus[];
}
export interface FileStatusesRootObject {
FileStatuses: FileStatuses;
}
and then
return this.http.get<FileStatusesRootObject>(
You need to make sure the data types match. It expects a result of type FileStatus[]. Thus, on your RxJS's map(), you will need to return the right data respectively by selecting FileStatus, which contains the array of objects with the type of FileStatus
public getHadoopDirList(): Observable<FileStatus[]> {
return this.http.get<FileStatus[]>(this.webHdfsUrl, {})
.pipe(
map(data => data['FileStatuses']['FileStatus'])
);
}