How to retrieve the value of a json object from Mysql in Graphql - mysql

import { GraphQLString, GraphQLScalarType } from 'graphql'
import { city } from '../../Entities/Cities'
export const CREATE_CITY = {
type: Citytype,
args: {
Name: { type: GraphQLString },
CountryCode: { type: GraphQLString },
District: { type: GraphQLString },
Info: { type: GraphQLString }
},
resolve(parent: any, args: any) {
const { Name, CountryCode, District, Info } = args;
city.insert({ Name, CountryCode, District, Info });
return args;
},
}`
import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from "typeorm";
#Entity()
export class city extends BaseEntity{
#PrimaryGeneratedColumn()
Id!: number;
#Column({ type: "char", length: 35 })
Name!: string;
#Column({ type: "char", length: 3 })
CountryCode!: string;
#Column({ type: "char", length: 20 })
District!: string;
#Column({ type: "string" })
Info!: string;
}
<I'm trying to learn graphql and I'm a day in>
The Info type is suppose to be a json, in my database it looks like {"Population": 127800} with the same definition. I'm fully aware that it isn't a string/GraphQLString but I don't know how to obtain the value of this object. It returns Info: null and an error - "message": "String cannot represent value: { Population: 127800 }" for obvious reasons.
The code has the same structure as the tutorial I watched and only this video.
Link: https://www.youtube.com/watch?v=fov5e6XJgwc&ab_channel=PedroTech
Q: I want to know how to get the population ex. {"Population": 127800} when I query
it should look like Info: {"Population": 127800}
Optional: How to get the value of population if it looks like - Info: 127800

Related

How to declare an interface with an array of objects in Angular (typescript)?

I created an Angular project where I'm receiving an object with the following structure from the backend:
{
status: "ok",
totalResults: 12,
articles: [
{
source: {
id: null,
name: "Sports Illustrated"
},
author: "Albert Breer",
title: "Some Title",
description: "Some description",
urlToImage: "http://google.ch/someImage.jpg"
}
]
}
I then tried to create an interface which corresponds to this object. Yet I struggled to define properties that refer to an object resp. an array of objects (e.g. article).
In my first attempt I tried to define my object inline:
export interface Noticias {
status: string;
totalResults: number;
articles: Array<{
id: string;
name: string;
title: string;
description: string;
urlToImage: string;
}>
}
Then I tried to define the properties as duplicates:
export interface Noticias {
status: string;
totalResults: number;
id: string;
name: string;
title: string;
description: string;
urlToImage: string;
articles: Array<{
id: string;
name: string;
title: string;
description: string;
urlToImage: string;
}>
}
Visual Studio Code keeps showing me errors, therefore I doubt whether my approach is correct. Any help would be greatly appreciated!
Based on the json-structure on your first screenshot you'd rather create three separate interfaces: One for Noticias, one for Article and one for Source. Then Noticias contains an array of type Article and Article contains an object of type Source;
noticias.model.ts:
import { Article } from './article.model';
export interface Noticias {
status: string;
totalResults: number;
articles: Article[];
}
article.model.ts:
import { Source } from './source.model';
export interface Article {
source: Source;
author: string;
title: string;
description: string;
urlToImage: string;
}
source.model.ts:
export interface Source {
id: string;
name: string;
}

Sequelize ModelNotInitializedError, Object need to be added to a Sequelize instance

I get this error when i run my project.
ModelNotInitializedError: Model not initialized: Member "getTableName"
cannot be called. "Categorie" needs to be added to a Sequelize
instance.
User model :
import { Categorie } from './categorie.model';
import sequelize from './index'
import { Model } from 'sequelize-typescript'
interface UserAttributes {
firstname: string;
lastname: string;
email: string;
password: string;
phone: string;
address: string;
}
export class User extends Model<UserAttributes> implements UserAttributes {
public firstname!: string;
public lastname!: string;
public email!: string;
public password!: string;
public phone!: string;
public address!: string;
public getCategories!: BelongsToManyGetAssociationsMixin<Categorie>;
public addCategories!: BelongsToManyAddAssociationMixin<Categorie, number>;
public hasCategories!: BelongsToManyHasAssociationMixin<Categorie, number>;
public countCategories!: BelongsToManyCountAssociationsMixin;
public createCategories!: BelongsToManyCreateAssociationMixin<Categorie>;
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
}
User.init({
// id: {
// type: DataTypes.INTEGER.UNSIGNED,
// autoIncrement: true,
// primaryKey: true,
// },
firstname: {
type: new DataTypes.STRING(128),
allowNull: false,
},
lastname: {
type: new DataTypes.STRING(128),
allowNull: false,
},
email: {
type: new DataTypes.STRING(128),
allowNull: false,
unique: true,
},
password: {
type: new DataTypes.STRING(128),
allowNull: false,
},
phone: {
type: new DataTypes.STRING(64),
allowNull: false,
},
address: {
type: new DataTypes.STRING(256),
allowNull: false,
},
}, {
tableName: 'User',
sequelize
})
User.belongsToMany(Categorie, {through: 'User_Cat'});
Categorie.belongsToMany(User, {through: 'User_Cat'});
sequelize.sync();
Categorie model :
import { BelongsToManyAddAssociationMixin, BelongsToManyCountAssociationsMixin, BelongsToManyCreateAssociationMixin, BelongsToManyGetAssociationsMixin, BelongsToManyHasAssociationMixin, DataTypes } from 'sequelize';
import sequelize from './index'
import { Model } from 'sequelize-typescript'
import { Unit } from './unit.model';
interface CategorieAttributes {
index: number;
title: string;
img: string;
label: string;
eval_intro: string;
eval_mid: string;
}
export class Categorie extends Model<CategorieAttributes> implements CategorieAttributes {
public index!: number;
public title!: string;
public img!: string;
public label!: string;
public eval_intro!: string;
public eval_mid!: string;
public getUnits!: BelongsToManyGetAssociationsMixin<Unit>;
public addUnits!: BelongsToManyAddAssociationMixin<Unit, number>;
public hasUnits!: BelongsToManyHasAssociationMixin<Unit, number>;
public countUnits!: BelongsToManyCountAssociationsMixin;
public createUnits!: BelongsToManyCreateAssociationMixin<Unit>;
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
}
Categorie.init({
// id: {
// type: DataTypes.INTEGER.UNSIGNED,
// autoIncrement: true,
// primaryKey: true,
// },
index: {
type: DataTypes.INTEGER.UNSIGNED,
allowNull: true,
},
title: {
type: new DataTypes.STRING(256),
allowNull: false,
},
img: {
type: new DataTypes.STRING(256),
allowNull: true,
},
label: {
type: new DataTypes.TEXT,
allowNull: false,
},
eval_intro: {
type: new DataTypes.STRING(256),
allowNull: true,
},
eval_mid: {
type: new DataTypes.STRING(256),
allowNull: true,
}
}, {
tableName: 'Categorie',
sequelize
})
Categorie.belongsToMany(Unit, { through: 'Cat_Unit' });
Unit.belongsToMany(Categorie, { through: 'Cat_Unit' });
sequelize.sync();
relation file :
interface UserCatAttributes {
id: number;
UserId: number;
CategorieId: number;
prog: number;
}
export class UserCat implements UserCatAttributes {
public id!: number;
public UserId!: number;
public CategorieId!: number;
public prog!: number;
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
}
And my main file :
import express from 'express';
import { Express } from "express-serve-static-core";
import { Sequelize } from 'sequelize';
import { User } from './models/user.model';
import { Categorie } from './models/categorie.model';
import { Unit } from './models/unit.model';
import { UserCat } from './models/user_cat.model';
import { initRoutes } from './routes/index';
import { sequelize_config } from './config/sequelizeConfig';
import passport from 'passport';
import cors from 'cors';
const port: number = 8080;
class Beyond {
public app: Express;
public sequelize: Sequelize;
constructor() {
this.initApp()
}
initApp() {
this.initExpress()
this.initSequelize()
}
initExpress() {
this.app = express();
this.app.use(cors({
optionsSuccessStatus: 200
}))
this.app.use(express.json());
this.app.use(passport.initialize());
this.app.use(passport.authenticate('session'));
initRoutes(this.app);
this.app.listen(port, () => {
console.log("Serveur à l'écoute sur le port : ", port)
})
}
async initSequelize() {
this.sequelize = new Sequelize(
sequelize_config.db_name,
sequelize_config.db_user,
sequelize_config.db_pw,
sequelize_config.sequelize_info as any
);
await this.sequelize.authenticate().then(() => {
console.log("Connexion ok")
}).catch(err => {
console.log("err connexion : ", err)
})
}
}
export const beyond = new Beyond();
All i want to do is a many to many relation, where User can have many Categorie and Categorie many User.
What driving me crazy is everything was working perfectly before idk what event, the tables where created and all the backend has been made with thooses models
ex
export async function getCatByUserId(id: number): Promise<Array<Categorie>> {
const user = await User.findByPk(id, { include: Categorie });
return await user.getCategories();
}
and since then no way to make it works. I'am far for being a pro so any help is appreciated.
You need to remove cross-references from model modules and define functions to register associations and call them after all your models will be registered in Sequelize instance.
See my answer here to get an idea of how to do it.

sequelize with typescript can not use .create with type attributes

The IDBAttribute -
interface IDBAtribute {
readonly id: number;
readonly createdAt: Date;
readonly updatedAt: Date;
}
The User attributes -
interface IDBMoviesAttributes extends IDBAttribute {
readonly title: string;
readonly description: string;
readonly category: string;
readonly release_date: number;
readonly movie_hour_length: number;
readonly movie_minute_length: number;
readonly image_path: string;
readonly video_path: string;
}
The User model -
import { BuildOptions, DataTypes, Model, Sequelize } from "sequelize";
import { IDBUserAttributes } from "./shared/db-table";
interface UserModel extends Model<IDBUserAttributes>, IDBUserAttributes {}
class User extends Model<UserModel, IDBUserAttributes> {}
type UserStatic = typeof Model & {
new (values?: object, options?: BuildOptions): UserModel;
};
const UserFactory = (sequelize: Sequelize): UserStatic => {
return <UserStatic>sequelize.define("users", {
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true,
unique: true,
allowNull: false,
},
email: {
type: DataTypes.STRING(320),
allowNull: false,
unique: true,
},
username: {
type: DataTypes.STRING(26),
allowNull: false,
},
password: {
type: DataTypes.STRING(255),
allowNull: false,
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW,
},
updatedAt: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW,
},
});
}
export {
UserModel,
User,
UserFactory,
UserStatic,
}
I'm Using the User for .create method in sequelize like this -
User.create({
email: req.body.email,
username: req.body.username,
password: hashedPassword,
})
The error -
Argument of type '{ email: string; username: string; password: string; }' is not assignable to parameter of type 'IDBUserAttributes'.
Type '{ email: string; username: string; password: string; }' is missing the following properties from type 'IDBUserAttributes': id, createdAt, updatedAtts(2345)
I know to error is type error but i don't know any other why to the User model, is there any other way I can achive that? I don't need to create the id,createdAt, updatedAt.
How can I get the model in the correct way?
Try making id ,createdAt ,updatedAt as Optional(?) in IDBUserAttributes.
It might work
Example:
interface IDBUserAttributes {
id?: number;
createdAt?: Date;
updatedAt?: Date;
}
const newObjectData: Request['body'] = {
user_id: 1
};
and now, you can use "create" method like this;
await Model.create(newObjectData);

Angular4 error message shows code which differs from the code that's supposed to be serving

I'm writing an app to go into a website, which is intended to calculate simplex algorithms. At the moment I am attempting to create functionality whereby the user can enter the number of coefficients and constraints, name these whatever they wish, and have the app spawn the relevant number and type of UI elements relative to the user's input. Here's what appears to be the relevant portion of the code (app.component.ts):
import { Component } from '#angular/core';
[...]
export class UIComponent {
id: 1;
name: string;
value: number;
type: string;
}
//* Mock data */
const UICOMPONENTS: UIComponent[] = [
{ id: 1, name: 'coefficient1', value: 4, type: '1dslide' },
{ id: 2, name: 'constraint1', value: 2, type: '2dslide' },
{ id: 3, name: 'min_max', value: 0, type: 'switch' },
{ id: 4, name: 'profit', value: 100, type: 'num_output' }
];
[...]
export class AppComponent {
title = 'SimutronX';
uicomponents = UICOMPONENTS;
[...]
}
This produces an error on screen saying:
Failed to compile.
/root/simutronx/simutron-app/src/app/app.component.ts (18,49): ',' expected.
Which relates to this line:
{ id: 2, name: 'constraint1', value: 2, type: '2dslide' },
Specifically the digit 2 in 2dslide. The error message (it's extremely long so I won't reproduce it all) also includes:
./src/app/app.component.ts
Module parse failed: /root/simutronx/simutron-app/node_modules/#ngtools/webpack/src/index.js!/root/simutronx/simutron-app/src/app/app.component.ts Unexpected token (22:85)
You may need an appropriate loader to handle this file type.
| var UICOMPONENTS = [
| { id: 1, name: 'coefficient1', value: 4, type: '1dslide' },
| { id: 2, name: 'constraint1, value: 2, type: ', 2: dslide, ' },: { id: 3, name: 'min_max', value: 0, type: 'switch' }, },
| { id: 4, name: 'profit', value: 100, type: 'num_output' }
| ];
Which is particularly confusing since, as you can see, that's not how I wrote the code. What's going on here?
You have an error in UIComponent type :
export class UIComponent {
id: number; //HERE
name: string;
value: number;
type: string;
}
Here a plunker :http://plnkr.co/edit/e6GrylSWznwbYD9VpK2C

From JSON to Typescript interface

I'm going crazy.
I have this JSON:
{
'name': 'Help Me',
'filters': {
'filter1': {
'filter_id': 'wow',
'filter_query': 'maw',
},
'filter2': {
'filter_id': 'wow',
'filter_query': 'maw',
}
}
}
And i'm trying to get this in this way:
export interface MyObject {
name: string;
filters: Filters;
}
export interface Filters {
[key: string]: QueryFilter;
}
export interface QueryFilter {
filter_id: string;
filter_query: string;
friendly_filter_query: string;
}
Or in this way:
export interface MyObject {
name: string;
filters: Map<string, QueryFilter[]>;}
But in first case i got this error message:
Property 'filters' is missing in type '{ 'name': string; ...'.
And in the second case i got this:
Property 'clear' is missing in type '{ 'filter1': { 'filter_id': string; 'filter_query': string; }...'.
I really can't figure out.