-
-
Save luismendes070/905e3202ec714c24cdd17dee5e722acb to your computer and use it in GitHub Desktop.
// Angular HTTP API | Part 27 - Sending PATCH Request 2 https://youtu.be/if90tYBdCsg | |
patchXml(course:Course): Observable<Course>{ | |
return this.http.patch<Course>('${this.apiUrl}/courses/id/${courses.id}', course); | |
} | |
// git fork curso especialista Angular Loiane Groner | |
git clone https://github.com/luismendes070/curso-angular.git | |
new repo git pull large file system | |
https://github.com/luismendes070/crud-xml-git-pull/tree/master | |
node --version | |
v18.12.1 | |
SCSS or CSS | |
https://sass-lang.com/documentation/syntax#scss | |
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned | |
ng --version | |
VSCode Extension Java + Spring | |
VSCode Extension TypeScript Hero | |
cd my-app | |
ng serve --open | |
ng add @angular/material | |
ng g m courses | |
ng g m courses --routing | |
ng g c courses/courses | |
@angular/core 15.0.4 | |
Problem https://stackoverflow.com/questions/73639394/ng0303-cant-bind-to-ngforof-since-it-isnt-a-known-property-of-div-used-i | |
Solution ? | |
Problem https://stackoverflow.com/questions/56597917/need-help-in-connecting-mongodb-to-vs-code | |
Solution IntelliJ Ultimate |
`npm install bson @types/bson
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { BSON } from 'bson';
@Injectable({
providedIn: 'root'
})
export class BSONService {
private baseUrl = 'http://localhost:3000/api'; // Your API URL
constructor(private http: HttpClient) { }
create(data: any): Observable {
const payload = { data: new BSON().serialize(data) };
return this.http.post(${this.baseUrl}/create
, payload)
.pipe(map(response => new BSON().deserialize(response)));
}
read(id: string): Observable {
return this.http.get(${this.baseUrl}/read/${id}
)
.pipe(map(response => new BSON().deserialize(response)));
}
update(id: string, data: any): Observable {
const payload = { data: new BSON().serialize(data) };
return this.http.put(${this.baseUrl}/update/${id}
, payload)
.pipe(map(response => new BSON().deserialize(response)));
}
delete(id: string): Observable {
return this.http.delete(${this.baseUrl}/delete/${id}
)
.pipe(map(response => new BSON().deserialize(response)));
}
}
`
` import { Component } from '@angular/core';
import { BSONService } from './bson.service';
@component({
selector: 'app-root',
template: '<button (click)="createDocument()">Create document'
})
export class AppComponent {
constructor(private bsonService: BSONService) { }
createDocument(): void {
const data = { name: 'John', age: 30 };
this.bsonService.create(data).subscribe(response => {
console.log(response);
});
}
}
`
The postgreSQL CRUD XML DataService #medium #ChatGPT feature
https://javascript.plainenglish.io/stream-xml-file-to-postgresql-with-nodejs-564f18ec7840
`import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Pool, PoolClient } from 'pg';
import * as pgCopyStreams from 'pg-copy-streams';
import XmlStream from 'xml-stream';
@ Injectable({
providedIn: 'root'
})
export class DataService {
private pool: Pool;
constructor(private http: HttpClient) {
this.pool = new Pool({
user: 'postgres',
password: 'admin',
host: 'localhost',
database: 'postgres',
port: 5432
});
}
public importData(): void {
const query = "COPY currency_rate (symbol, rate, info_date) FROM STDIN WITH DELIMITER ','";
this.pool.connect((err: Error, client: PoolClient, release: (release?: any) => void) => {
const dbStream = client.query(pgCopyStreams.from(query))
.on('error', error => {
release();
console.log(error);
})
.on('finish', () => {
release();
const endTime = process.hrtime(startTime);
console.log('Data transfer to database is done!');
console.log('Execution time: %ds %dms', endTime[0], endTime[1] / 1000000);
});
const xmlUrl = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist.xml';
this.http.get(xmlUrl, { responseType: 'text' }).subscribe(data => {
const xml = new XmlStream(data);
xml.collect('Cube');
xml.on('updateElement: gesmes:Envelope > Cube > Cube', (tag: any) => {
tag.Cube.map((subTag: any) => `${subTag.$.currency},${subTag.$.rate},${tag.$.time}\n`)
.forEach((item: any) => dbStream.write(item));
});
xml.on('end', () => dbStream.end());
xml.on('error', (error: Error) => console.log(error));
}, error => console.log(error));
});
}
}
`
Or axios posgreSQL CRUD XML DataService #medium #ChatGPT feature
Git fork RocketSeat
https://github.com/luismendes070/youtube-upload-nodejs-reactjs-frontend
https://github.com/luismendes070/youtube-upload-nodejs-reactjs-backend
`import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Pool, PoolClient } from 'pg';
import * as pgCopyStreams from 'pg-copy-streams';
import XmlStream from 'xml-stream';
import axios from 'axios';
@Injectable({
providedIn: 'root'
})
export class DataService {
private pool: Pool;
constructor(private http: HttpClient) {
this.pool = new Pool({
user: 'postgres',
password: 'admin',
host: 'localhost',
database: 'postgres',
port: 5432
});
}
public importData(): void {
const query = "COPY currency_rate (symbol, rate, info_date) FROM STDIN WITH DELIMITER ','";
this.pool.connect((err: Error, client: PoolClient, release: (release?: any) => void) => {
const dbStream = client.query(pgCopyStreams.from(query))
.on('error', error => {
release();
console.log(error);
})
.on('finish', () => {
release();
const endTime = process.hrtime(startTime);
console.log('Data transfer to database is done!');
console.log('Execution time: %ds %dms', endTime[0], endTime[1] / 1000000);
});
const xmlUrl = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist.xml';
axios.get(xmlUrl, { responseType: 'text' }).then(response => {
const xml = new XmlStream(response.data);
xml.collect('Cube');
xml.on('updateElement: gesmes:Envelope > Cube > Cube', (tag: any) => {
tag.Cube.map((subTag: any) => `${subTag.$.currency},${subTag.$.rate},${tag.$.time}\n`)
.forEach((item: any) => dbStream.write(item));
});
xml.on('end', () => dbStream.end());
xml.on('error', (error: Error) => console.log(error));
}).catch(error => console.log(error));
});
}
}
`
New git clone fixed git-lfs broken TypeScript repo
[](git-lfs/git-lfs#4191
git-lfs/git-lfs#2503
git-lfs/git-lfs#4974)
broken-git-repo-after-git-lfs-migrate
exit root Ubuntu
Angular Sequelize ORM
`import { Sequelize } from 'sequelize';
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'postgres',
});
`
`import { Model, DataTypes } from 'sequelize';
class MyModel extends Model {}
MyModel.init(
{
xmlData: {
type: DataTypes.TEXT,
allowNull: false,
},
},
{
sequelize,
modelName: 'MyModel',
}
);
export default MyModel;
`
DataService Angular
`import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import MyModel from './models/my-model.model';
@Injectable({
providedIn: 'root',
})
export class DataService {
private readonly baseUrl = 'http://localhost:3000';
constructor(private readonly http: HttpClient) {}
create(data: any): Observable {
return this.http.post(${this.baseUrl}/my-models
, data);
}
read(id: number): Observable {
return this.http.get(${this.baseUrl}/my-models/${id}
);
}
update(id: number, data: any): Observable {
return this.http.put(${this.baseUrl}/my-models/${id}
, data);
}
delete(id: number): Observable {
return this.http.delete(${this.baseUrl}/my-models/${id}
);
}
readAll(): Observable<MyModel[]> {
return this.http.get<MyModel[]>(${this.baseUrl}/my-models
);
}
}
`
ModeList Angular Web Component
`import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import MyModel from '../models/my-model.model';
@component({
selector: 'app-my-model-list',
templateUrl: './my-model-list.component.html',
})
export class MyModelListComponent implements OnInit {
myModels: MyModel[] = [];
constructor(private readonly dataService: DataService) {}
ngOnInit(): void {
this.dataService.readAll().subscribe((myModels) => {
this.myModels = myModels;
});
}
deleteMyModel(id: number): void {
this.dataService.delete(id).subscribe(() => {
this.myModels = this.myModels.filter((myModel) => myModel.id !== id);
});
}
}
`
MyModelFormComponent Angular
`import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { DataService } from '../data.service';
@component({
selector: 'app-my-model-form',
templateUrl: './my-model-form.component.html',
})
export class MyModelFormComponent implements OnInit {
myModelForm: FormGroup;
isEditing: boolean = false;
id: number;
constructor(
private readonly formBuilder: FormBuilder,
private readonly dataService: DataService,
private readonly route: ActivatedRoute,
private readonly location: Location
) {}
ngOnInit(): void {
this.myModelForm = this.formBuilder.group({
xmlData: ['', Validators.required],
});
this.route.params.subscribe((params) => {
if (params['id']) {
this.isEditing = true;
this.id = +params['id'];
this.dataService.read(this.id).subscribe((myModel) => {
this.myModelForm.patchValue(myModel);
});
}
});
}
save(): void {
if (this.myModelForm.valid) {
const formData = new FormData();
formData.append('xmlData', this.myModelForm.get('xmlData').value);
if (this.isEditing) {
this.dataService.update(this.id, formData).subscribe(() => {
this.location.back();
});
} else {
this.dataService.create(formData).subscribe(() => {
this.location.back();
});
}
}
}
cancel(): void {
this.location.back();
}
}
`
npm install --save sequelize sequelize-typescript pg pg-hstore xml2js
`import { Table, Column, Model, DataType } from 'sequelize-typescript';
@table({ tableName: 'my_table' })
export class MyModel extends Model {
@column({ type: DataType.STRING })
name!: string;
@column({ type: DataType.STRING })
description!: string;
@column({ type: DataType.DATE })
date!: Date;
}
`
sequelize.ts
`import { Sequelize } from 'sequelize-typescript';
import { MyModel } from './models/MyModel';
export const sequelize = new Sequelize({
dialect: 'postgres',
database: 'my_database',
username: 'my_username',
password: 'my_password',
host: 'localhost',
port: 5432,
logging: false,
});
sequelize.addModels([MyModel]);
export async function syncDB() {
await sequelize.sync({ force: true });
}
`
my-service.ts
`import { Injectable } from '@angular/core';
import { from, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { MyModel } from '../models/MyModel';
import { sequelize } from '../sequelize';
@Injectable()
export class MyService {
private readonly myModel = MyModel;
create(data: any): Observable {
return from(this.myModel.create(data));
}
findAll(): Observable<MyModel[]> {
return from(this.myModel.findAll()).pipe(map((data) => data as MyModel[]));
}
findById(id: number): Observable {
return from(this.myModel.findByPk(id)).pipe(map((data) => data as MyModel));
}
update(id: number, data: any): Observable {
return from(this.myModel.update(data, { where: { id } })).pipe(
map(() => this.findById(id))
);
}
delete(id: number): Observable {
return from(this.myModel.destroy({ where: { id } })).pipe(map(() => {}));
}
}
`
db.ts
`import { Sequelize } from "sequelize";
const sequelize = new Sequelize({
dialect: "postgres",
host: process.env.DB_HOST,
port: process.env.DB_PORT,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
});
export default sequelize;
`
install Travis lubuntu 22 maven-prettier-plugin
`
#!/bin/bash
Add Travis Lubuntu Linux 22 repository
sudo add-apt-repository "deb http://archive.travis-ci.org/ubuntu trusty main"
Add Travis CI public key to apt-key
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 3B4FE6ACC0B21F32
Update the package list
sudo apt-get update
Install Travis Lubuntu Linux 22
sudo apt-get install -y travis-lubuntu
Verify that Travis Lubuntu Linux 22 is installed
travis-lubuntu version
`
chmod + x permission
https://github.com/FasterXML/jackson-dataformat-xml
<dependency> <groupId>com.fasterxml.woodstox</groupId> <artifactId>woodstox-core</artifactId> <version>6.2.5</version> </dependency>
Vercel CORS
const express = require('express');
const app = express();
// Set CORS headers
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') {
return res.sendStatus(200);
}
next();
});
// Your API routes go here...
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class CorsInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const headers = req.headers
.set('Access-Control-Allow-Origin', '*')
.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
const corsReq = req.clone({ headers });
return next.handle(corsReq);
}
}
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MyCrudService {
private apiUrl = 'http://example.com/api';
constructor(private http: HttpClient) { }
getAll(): Observable<any> {
return this.http.get(`${this.apiUrl}/items`);
}
create(data: any): Observable<any> {
return this.http.post(`${this.apiUrl}/items`, data);
}
update(id: number, data: any): Observable<any> {
return this.http.put(`${this.apiUrl}/items/${id}`, data);
}
delete(id: number): Observable<any> {
return this.http.delete(`${this.apiUrl}/items/${id}`);
}
}
ng generate interceptor auth --skip-tests=true
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
const authToken = 'my-auth-token';
const authReq = req.clone({
headers: req.headers.set('Authorization', `Bearer ${authToken}`)
});
return next.handle(authReq);
}
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { AuthInterceptor } from './auth.interceptor';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule {}
NextJS Secure XML loading for Angular CRUD XML #ChatGPT
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) {}
this.http.get('https://example.com/api/xml-data').subscribe(data => {
console.log(data); // logs the fetched XML data
});
import { HttpClient, HttpHeaders } from '@angular/common/http';
const headers = new HttpHeaders({
'Content-Type': 'application/xml', // or any other appropriate content type
'Access-Control-Allow-Origin': '*', // or the domain of your Angular app
});
this.http.get('https://example.com/api/xml-data', { headers }).subscribe(data => {
console.log(data); // logs the fetched XML data
});
Insomnia stress testing k6, locust, loader #BingChat
[ ] Angular
[ ] Java Spring Boot
k6 JavaScript
`import http from 'k6/http';
import {sleep} from 'k6';
export const options = {
stages: [
{ duration: '10m', target: 200 }, // ramp-up from 1 to 200 users over 10 minutes.
{ duration: '30m', target: 200 }, // stay at 200 users for 30 minutes
{ duration: '5m', target: 0 }, // ramp-down to 0 users
],
};
export default () => {
const urlRes = http.get('https://test-api.k6.io');
};
`
https://stackblitz.com/edit/angular-5l72bc?file=src/app/app.component.ts
https://angular-5l72bc.stackblitz.io
https://stackoverflow.com/questions/54630667/rendering-xml-in-angular-2