Typeorm pool doesn't exist in replication - mysql

typegraphql, typeorm, Mysql with master slave replication.
I have configured mysql with master and slave databases with separate instances and its working fine. I have encounter an error
while connecting via typeorm. Here's my ormconfig.json
{
"type": "mysql",
"logging": true,
"replication": {
"master":
{
"host": "192.168.0.250",
"port": 3306,
"username": "root",
"password": "test#123",
"database": "master",
"synchronize": true,
"extra": {
"connectionLimit": 5
}
}
,
"slaves": [
{
"host": "192.168.0.175",
"port": 3306,
"username": "root",
"password": "test#123",
"database": "master",
"synchronize": true,
"extra": {
"connectionLimit": 5
}
}
]
},
"entities": [
"src/entity/**/*.ts"
],
"migrations": [
"src/migration/**/*.ts"
],
"subscribers": [
"src/subscriber/**/*.ts"
],
"cli": {
"entitiesDir": "src/entity",
"migrationsDir": "src/migration",
"subscribersDir": "src/subscriber"
}
}
My index.ts file with database connection as
import { gqSchema } from './schema';
import "reflect-metadata";
import { createConnection } from "typeorm";
import { ApolloServer } from "apollo-server";
async function main() {
await createConnection().then(async(res) => {
console.log(res)
console.log("Database Connected")
const schema = await gqSchema()
const server = new ApolloServer({
schema,
context: ({ req }: any) => ({ req })
})
await server.listen(4000)
console.log("Server has started!")
}).catch(err => {
console.log("err", err)
})
}
main();
And my resolver.ts file
#Resolver()
export class UserResolver {
/**
* query
*/
#Authorized()
#Query(() => User)
async hello(
#Arg("firstName") firstName: string,
): Promise<User | undefined > {
const slaveQueryRunner = getConnection().createQueryRunner("slave");
try {
const connection = getConnection().getRepository(User);
const usersList = await connection.createQueryBuilder()
.from(User, "user")
.setQueryRunner(slaveQueryRunner)
.where("user.firstName = ", {firstName})
.getOne();
console.log(usersList)
} finally {
slaveQueryRunner.release();
}
}
}

Related

Typeorm Multiple DB Node

Hello how are you? I'm trying to connect two different databases in a project. I'm creating one mysql and one postgres, using typeorm. But I'm not able to use mysql. Does anyone know how to resolve this error?
ormconfig.json:
[
{
"name": "default",
"type": "postgres",
"port": 5432,
"host": "localhost",
"username": "admin",
"password": "admin",
"database": "first",
"migrations": [
"./src/database/migrations/firstClient/*.ts"
],
"entities": [
"./src/modules/firstClient/entities/*.ts"
],
"cli": {
"migrationsDir": "./src/database/migrations/firstClient"
}
},
{
"name": "connection2",
"type": "mysql",
"port": 3306,
"host": "localhost",
"username": "admin",
"password": "admin",
"database": "second",
"migrations": [
"./src/database/migrations/secondClient/*.ts"
],
"entities": [
"./src/modules/secondClient/entities/*.ts"
],
"cli": {
"migrationsDir": "./src/database/migrations/secondClient"
}
}
]
database/index.ts:
import { createConnections, getConnectionOptions } from 'typeorm';
getConnectionOptions().then(() => {
createConnections();
});
entities/Client.ts:
import { v4 as uuidv4 } from 'uuid';
import { Entity, PrimaryColumn, Column } from 'typeorm';
#Entity({ database: 'connection2', name: 'contacts' })
class Client {
#PrimaryColumn()
id?: string;
#Column('varchar')
name: string;
#Column('varchar')
cellphone: string;
constructor() {
if (!this.id) {
this.id = uuidv4();
}
}
}
export { Client };
and in repositories/implementations/clientReporitory I import my entity:
import { Repository, getRepository } from 'typeorm';
import { Client } from '../../entities/Client';
import { IClientsRepository, ICreateClientDTO } from '../IClientsRepository';
class ClientsRepository implements IClientsRepository {
private repository: Repository<Client>;
constructor() {
this.repository = getRepository(Client);
}
async findByCellphone(cellphone: string): Promise<Client> {
const client = await this.repository.findOne({ cellphone });
return client;
}
async list(): Promise<Client[]> {
const clients = await this.repository.find();
return clients;
}
async createMultiple(contacts: Client[]): Promise<void> {
const clients = this.repository.create(contacts);
await this.repository.save(clients);
}
async create({ name, cellphone }: ICreateClientDTO): Promise<void> {
const client = this.repository.create({ name, cellphone });
await this.repository.save(client);
}
async update({ name, cellphone, id }: ICreateClientDTO): Promise<void> {
await this.repository.update({ id }, { name, cellphone });
}
async delete(id: string): Promise<void> {
await this.repository.delete({ id });
}
}
export { ClientsRepository };
if I run typeorm migration:run passing the connection it does the migration in mysql and postgres
typeorm migration:run -c "connection2"

How can we get data from mysql database in angular 7 application by using node.js and display it on angular component html page

I have tried every thing but i cant under stand how to reach my goal.
Now my main goal is that i want to get data from mysql database and then access this information in angular component which is page-one.component.ts file. Now i can connect to the database and can get the data from database in server.js file. but i cant understand how to get the information in angular component. The method i have tried so far is that i include the server.js file in angular.json file and then include the function "get_data" (get_data function fetch data from database in server.js file) in my page-one.component.ts file and then i call the function in page-one.component.ts file. The function is called, but the problem is that i got error in server.js file that " Cannot read property 'createConnection' of undefined". This error stops me from getting the information from database. but when i call this get_data function in server.js file i got the database information and i can print the information in console.
Can any one give me the solution please.
I think the error is because of the context of variable.
but please guide me.
My server.js file code.
const express = require('express');
const path = require('path');
const http = require('http');
const socketIO = require('socket.io');
const app = express();
const server = http.createServer(app);
const port = process.env.PORT || 3000;
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
var mysql = require('mysql');
var dbconfig = {
host: "localhost",
user: "root",
password: "",
database: "mydb"
}
var con = mysql.createConnection(dbconfig);
con.connect(function (err) {
if (err) throw err;
console.log("Connected!");
});
get_data();
function get_data(){
console.log("function called");
var con = this.mysql.createConnection(dbconfig); ===> GOT ERROR HERE
con.query("SELECT * FROM teacher", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
}
server.listen(port, () => {
console.log(`server running on port ${port} `);
})
My page-one.component.ts file code.
import { Component, OnInit } from '#angular/core';
import { Http } from '#angular/http';
declare function get_data(): any;
#Component({
selector: 'app-page-one',
templateUrl: './page-one.component.html',
styleUrls: ['./page-one.component.css']
})
export class PageOneComponent implements OnInit {
constructor(private http: Http) { }
ngOnInit() {
get_data();
}
}
My angular.json file code.
{
"$schema": "./node_modules/#angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"myapp": {
"root": "",
"sourceRoot": "src",
"projectType": "application",
"prefix": "app",
"schematics": {},
"architect": {
"build": {
"builder": "#angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/myapp",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts":
[
"server.js" ===> INCULDED THE SERVER.JS FILe HERE
]
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true
}
}
},
"serve": {
"builder": "#angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "myapp:build"
},
"configurations": {
"production": {
"browserTarget": "myapp:build:production"
}
}
},
"extract-i18n": {
"builder": "#angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "myapp:build"
}
},
"test": {
"builder": "#angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.spec.json",
"karmaConfig": "src/karma.conf.js",
"styles": [
"src/styles.css"
],
"scripts": [],
"assets": [
"src/favicon.ico",
"src/assets"
]
}
},
"lint": {
"builder": "#angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"src/tsconfig.app.json",
"src/tsconfig.spec.json"
],
"exclude": [
"**/node_modules/**"
]
}
}
}
},
"myapp-e2e": {
"root": "e2e/",
"projectType": "application",
"architect": {
"e2e": {
"builder": "#angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "myapp:serve"
},
"configurations": {
"production": {
"devServerTarget": "myapp:serve:production"
}
}
},
"lint": {
"builder": "#angular-devkit/build-angular:tslint",
"options": {
"tsConfig": "e2e/tsconfig.e2e.json",
"exclude": [
"**/node_modules/**"
]
}
}
}
}
},
"defaultProject": "myapp"
}
" Cannot read property 'createConnection' of undefined"
const mysql = require('mysql2');
const connection = mysql.createPool({
host: 'localhost',
user: '',
password: '',
database: '',
connectionLimit: 10,
queueLimit: 0
});
connection.promise((err) => {
if (err) throw err;
console.log('connected!');
});
module.exports = connection.promise();
app.get("/youroute", (req, res, next) => {
"use strict";
const getProduct = "SELECT * FROM yourtable";
database.query(getProduct, (err, rows, fields) => {
if (err) {
res.status(500).send({ error: 'Something failed!' })
};
res.status(200).json({
message: "",
product: rows,
});
});
});
Service for Angular
export interface You {
id: number,
title: string,
content: string
}
Get Method on Model Angular
getData() {
this.http.get<{message:string,name:Name[]}>("URL")
.subscribe(result =>{
console.log(result);
});
and in HTML make For Loop with NGFOR for display your data

Iterate a JSON array by a key value in react-native

Is there anyway to get a value in an object from a json array. I need to get a value from an object based on another value.
I have my code like:
export default class StandardComp extends Component {
constructor(props) {
super(props)
this.state = {
id: '',
email: 'abc#gmail.com',
dataSource: []
};
}
componentDidMount(){
fetch(someURL, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({dataSource: responseJson})
//dunno what to do here
})
.catch((error) => {
console.error(error);
})
}
}
My "responseJson" is something like this. Then providing the key value (abc#gmail.com), how could I get the string "abcdef"?
[
{
"id": "qwerty",
"email": "cat#gmail.com",
"name": "cat"
},
{
"id": "abcdef",
"email": "abc#gmail.com",
"name": "abc"
}
{
"id": "owowao",
"email": "dog#gmail.com",
"name": "dog"
},
]
Thank you in advance.
Find the element that matches email and return the id.
array::find
const data = [
{
"id": "qwerty",
"email": "cat#gmail.com",
"name": "cat"
},
{
"id": "abcdef",
"email": "abc#gmail.com",
"name": "abc"
},
{
"id": "owowao",
"email": "dog#gmail.com",
"name": "dog"
},
];
const findIdByEmail = (data, email) => {
const el = data.find(el => el.email === email); // Possibly returns `undefined`
return el && el.id; // so check result is truthy and extract `id`
}
console.log(findIdByEmail(data, 'cat#gmail.com'));
console.log(findIdByEmail(data, 'abc#gmail.com'));
console.log(findIdByEmail(data, 'gibberish'));
The code will depend on how you get the value abc#gmail.com.
You'll probably need to pass it in as an argument to componentDidMount via a prop? Or extract it to a separate function. It just depends.
Something like this is the most basic way I'd say.
const value = responseJson.filter(obj => obj.email === 'abc#gmail.com')[0].id
Here it is implemented in your class.
export default class StandardComp extends Component {
...
componentDidMount(){
fetch(someURL, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({ dataSource: responseJson })
const { email } = this.state
const value = responseJson.filter(obj => obj.email === email)[0].id
})
.catch((error) => {
console.error(error);
})
}
}

Angular 4 find JSON data

I have this JSON: (this.url)
{
"user": [
{
"id": "1",
"name": "root",
"password": "root"
},
{
"id": "2",
"name": "clienttest",
"password": "123456"
}
]
}
and I have this service:
findUsers(id: number) : boolean {
return this.http.get(this.url)
.map((res: Response) => res.json());
.someOperator(to assert the id exist)...
}
I want to return true if the user was found.
Is there some operator like filter that can make this assert for me?
try to use Array.some() method:
findUsers(id: number) : boolean {
return this.http
.get(this.url)
.map((res: Response) => {
let result = res.json();
return result.user.some(user => parseInt(user.id) === id)
})
}
Inline simulation:
const data = {
"user": [
{
"id": "1",
"name": "root",
"password": "root"
},
{
"id": "2",
"name": "clienttest",
"password": "123456"
}
]
}
// this will simulate http get resolve being processed by res.json()
const httpGet = Rx.Observable.of(data);
const findUsers = id =>
httpGet.map(data => data.user.some(user => parseInt(user.id) === id))
;
findUsers(1).subscribe(result => console.log(result));
findUsers(3).subscribe(result => console.log(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.5/Rx.min.js"></script>

Angular2, get data from REST call

I'm triyng to get data from json file by a id, by I'm getting all the content.
Here the JSON:
[
{ "id": "1", "name": "Carlos", "apellidos":"López", "edad":"30", "ciudad":"Hospitalet" },
{ "id": "2", "name": "Arantxa", "apellidos":"Pavia", "edad":"24", "ciudad":"Barcelona" },
{ "id": "3", "name": "Didac" , "apellidos":"Pedra", "edad":"muchos", "ciudad":"Cornellà" },
{ "id": "4", "name": "Daniel" , "apellidos":"Farnos", "edad":"nolose", "ciudad":"Barcelona" }
]
Service:
private usersUrl = 'app/users.json';
getUser(id: String): Observable<User>{
let body = JSON.stringify(
{
"token": "test",
"content": {
"id": id
}
}
);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({
headers: headers,
body : body
});
return this.http.get(this.usersUrl, options)
.map(res => res.json()).catch(this.handleError);
}
Angular Component:
ngOnInit(){
this.route.params.subscribe(params => {
let id = +params['id'];
this.apiService.getUser(id).subscribe( (res) => { console.log(res); } );
})
}
Console.log:
Array[4]0: Object1: Object2: Object3: Objectlength: 4__proto__: Array[0]
Is the JSON bad?
Thanks.
Because you didn't filter the result by id.
.map(res => res.json())
.map(x > x.find(x => x.id == id) // filter by selected id
.catch(this.handleError);