React Native: Cannot get PeerJs server to communicate back to my React Native Client, sending back the peer ID - react-native

The example i found was here for the client:
https://github.com/metehankurucu/react-native-video-calling-app
So im trying to build the Server.js from this.
This is my Peer Client:
import React, {useState} from 'react';
import {Alert} from 'react-native';
import {
mediaDevices,
MediaStream,
MediaStreamConstraints,
} from 'react-native-webrtc';
import socketio from 'socket.io-client';
import {MainContext as MainContextType, User} from '../interfaces';
import {
SERVER_URL,
PEER_SERVER_HOST,
PEER_SERVER_PORT,
PEER_SERVER_PATH,
} from '../server';
// #ts-ignore
import Peer from 'react-native-peerjs';
import {navigate} from '../helpers/RootNavigation';
const initialValues: MainContextType = {
username: '',
peerId: '',
users: [],
localStream: null,
remoteStream: null,
remoteUser: null,
initialize: () => {},
setUsername: () => {},
call: () => {},
switchCamera: () => {},
toggleMute: () => {},
isMuted: false,
closeCall: () => {},
reset: () => {},
activeCall: null,
};
export const MainContext = React.createContext(initialValues);
interface Props {}
const MainContextProvider: React.FC<Props> = ({children}) => {
const [username, setUsername] = useState(initialValues.username);
const [peerId, setPeerId] = useState(initialValues.peerId);
const [users, setUsers] = useState<User[]>(initialValues.users);
const [localStream, setLocalStream] = useState<MediaStream | null>(
initialValues.localStream,
);
const [remoteStream, setRemoteStream] = useState<MediaStream | null>(
initialValues.remoteStream,
);
const [remoteUser, setRemoteUser] = useState<User | null>(null);
const [socket, setSocket] = useState<SocketIOClient.Socket | null>(null);
const [peerServer, setPeerServer] = useState<any>(null);
const [isMuted, setIsMuted] = useState(initialValues.isMuted);
const [activeCall, setActiveCall] = useState<any>(null);
const initialize = async () => {
const isFrontCamera = true;
const devices = await mediaDevices.enumerateDevices();
const facing = isFrontCamera ? 'front' : 'environment';
const videoSourceId = devices.find(
(device: any) => device.kind === 'videoinput' && device.facing === facing,
);
const facingMode = isFrontCamera ? 'user' : 'environment';
const constraints: MediaStreamConstraints = {
audio: true,
video: {
mandatory: {
minWidth: 1280,
minHeight: 720,
minFrameRate: 30,
},
facingMode,
optional: videoSourceId ? [{sourceId: videoSourceId}] : [],
},
};
const newStream = await mediaDevices.getUserMedia(constraints);
setLocalStream(newStream as MediaStream);
const io = socketio.connect('http://localhost', {
reconnection: true,
autoConnect: true,
});
io.on('connect', () => {
console.log('connect');
setSocket(io);
console.log('setSocket');
io.emit('register', username);
console.log('register');
});
io.on('users-change', (users: User[]) => {
console.log('users-change');
setUsers(users);
console.log('setUsers');
});
io.on('accepted-call', (user: User) => {
console.log('accepted-call');
setRemoteUser(user);
console.log('setRemoteUser');
});
io.on('rejected-call', (user: User) => {
console.log('rejected-call');
setRemoteUser(null);
console.log('setRemoteUser');
setActiveCall(null);
console.log('setActiveCall');
Alert.alert('Your call request rejected by ' + user?.username);
navigate('Users');
console.log('navigate');
});
io.on('not-available', (username: string) => {
console.log('not-available');
setRemoteUser(null);
console.log('setRemoteUser');
setActiveCall(null);
console.log('setActiveCall');
Alert.alert(username + ' is not available right now');
navigate('Users');
console.log('Users');
});
const peerServer = new Peer({
host: 'localhost',
path: '/peerjs',
secure: false,
port: 9000,
config: {
iceServers: [
{
urls: [
'stun:stun1.l.google.com:19302',
'stun:stun2.l.google.com:19302',
],
},
],
},
});
console.log(peerServer);
peerServer.on('error', (err: Error) =>
console.log('Peer server error', err),
);
peerServer.on('open', (peerId: string) => {
console.log('open');
setPeerServer(peerServer);
console.log('setPeerServer');
setPeerId(peerId);
console.log('setPeerId');
io.emit('set-peer-id', peerId);
console.log('set-peer-id');
});
io.on('call', (user: User) => {
console.log(user);
peerServer.on('call', (call: any) => {
console.log('call');
setRemoteUser(user);
console.log('setRemoteUser');
Alert.alert(
'New Call',
'You have a new call from ' + user?.username,
[
{
text: 'Reject',
onPress: () => {
io.emit('reject-call', user?.username);
setRemoteUser(null);
setActiveCall(null);
},
style: 'cancel',
},
{
text: 'Accept',
onPress: () => {
io.emit('accept-call', user?.username);
call.answer(newStream);
setActiveCall(call);
navigate('Call');
},
},
],
{cancelable: false},
);
call.on('stream', (stream: MediaStream) => {
console.log('stream');
setRemoteStream(stream);
console.log('setRemoteStream');
});
call.on('close', () => {
console.log('close');
closeCall();
console.log('closeCall');
});
call.on('error', () => {});
});
});
};
const call = (user: User) => {
if (!peerServer || !socket) {
Alert.alert('Peer server or socket connection not found');
return;
}
if (!user.peerId) {
Alert.alert('User not connected to peer server');
return;
}
socket.emit('call', user.username);
console.log('setRemoteUser');
setRemoteUser(user);
try {
console.log('1');
const call = peerServer.call(user.peerId, localStream);
console.log('peerServer.call(user.peerId, localStream)');
call.on(
'stream',
(stream: MediaStream) => {
setActiveCall(call);
setRemoteStream(stream);
},
(err: Error) => {
console.error('Failed to get call stream', err);
},
);
} catch (error) {
console.log('Calling error', error);
}
};
const switchCamera = () => {
if (localStream) {
// #ts-ignore
localStream.getVideoTracks().forEach((track) => track._switchCamera());
}
};
const toggleMute = () => {
if (localStream)
localStream.getAudioTracks().forEach((track) => {
track.enabled = !track.enabled;
setIsMuted(!track.enabled);
});
};
const closeCall = () => {
activeCall?.close();
setActiveCall(null);
setRemoteUser(null);
navigate('Users');
Alert.alert('Call is ended');
};
const reset = async () => {
peerServer?.destroy();
socket?.disconnect();
setActiveCall(null);
setRemoteUser(null);
setLocalStream(null);
setRemoteStream(null);
setUsername('');
setPeerId('');
};
return (
<MainContext.Provider
value={{
username,
setUsername,
peerId,
setPeerId,
users,
setUsers,
localStream,
setLocalStream,
remoteStream,
setRemoteStream,
initialize,
call,
switchCamera,
toggleMute,
isMuted,
closeCall,
reset,
remoteUser,
activeCall,
}}>
{children}
</MainContext.Provider>
);
};
export default MainContextProvider;
Forgive me as i have put alot of consol.logs in there, so i hope i havent confused you.
And this is my Peerjs Server:
const express = require("express");
const app = express();
const port = 9000;
const http = require("http");
const server = http.createServer(app);
const io = require("socket.io")(server);
app.use(express.static(__dirname + "/public"));
io.sockets.on("error", e => console.log(e));
server.listen(port, () => console.log(`Server is running on port ${port}`));
let broadcaster
io.sockets.on("connection", socket => {
socket.on("broadcaster", () => {
broadcaster = socket.id;
socket.broadcast.emit("broadcaster");
});
socket.on("watcher", () => {
socket.to(broadcaster).emit("watcher", socket.id);
});
socket.on("disconnect", () => {
socket.to(broadcaster).emit("disconnectPeer", socket.id);
});
});
this is the JSON i get from the client:
{
"acks": {},
"connected": false,
"disconnected": true,
"flags": {},
"ids": 0,
"io": {
"_autoConnect": true,
"_callbacks": {
"$close": [Array],
"$error": [Array],
"$open": [Array],
"$packet": [Array]
},
"_randomizationFactor": 0.5,
"_readyState": "opening",
"_reconnection": true,
"_reconnectionAttempts": Infinity,
"_reconnectionDelay": 1000,
"_reconnectionDelayMax": 5000,
"_timeout": 20000,
"backoff": {
"attempts": 0,
"factor": 2,
"jitter": 0.5,
"max": 5000,
"ms": 1000
},
"decoder": {},
"encoder": {},
"engine": {
"_callbacks": [Object],
"hostname": "localhost",
"id": null,
"opts": [Object],
"pingInterval": null,
"pingTimeout": null,
"pingTimeoutTimer": null,
"port": "80",
"prevBufferLen": 0,
"readyState": "opening",
"secure": false,
"transport": [XHR],
"transports": [Array],
"upgrades": null,
"writeBuffer": [Array]
},
"nsps": {
"/": [Circular]
},
"opts": {
"autoConnect": true,
"hostname": "localhost",
"path": "/socket.io",
"port": "80",
"reconnection": true,
"secure": false
},
"skipReconnect": false,
"subs": [
[Function subDestroy],
[Function subDestroy],
[Function subDestroy]
],
"uri": "http://localhost"
},
"nsp": "/",
"receiveBuffer": [],
"sendBuffer": [],
"subs": [
[Function subDestroy],
[Function subDestroy],
[Function subDestroy],
[Function subDestroy]
]
}
[Mon Mar 29 2021 19: 22: 16.595] LOG {
"_api": {
"_options": {
"config": [Object],
"debug": 0,
"host": "localhost",
"key": "peerjs",
"path": "/peerjs/",
"port": 9000,
"secure": false,
"token": "f0ty4c4n2si"
}
},
"_connections": Map {},
"_destroyed": false,
"_disconnected": false,
"_events": {},
"_eventsCount": 0,
"_id": null,
"_lastServerId": null,
"_lostMessages": Map {},
"_open": false,
"_options": {
"config": {
"iceServers": [Array]
},
"debug": 0,
"host": "localhost",
"key": "peerjs",
"path": "/peerjs/",
"port": 9000,
"secure": false,
"token": "f0ty4c4n2si"
},
"_socket": {
"_baseUrl": "ws://localhost:9000/peerjs/peerjs?key=peerjs",
"_disconnected": true,
"_events": {
"close": [r],
"disconnected": [r],
"error": [r],
"message": [r]
},
"_eventsCount": 4,
"_messagesQueue": [],
"pingInterval": 5000
}
}
[Mon Mar 29 2021 19: 22: 16.752] LOG Peer server error[Error: Could not get an ID from the server.]

Related

sequelize scope inverse( exclude ) records

I have 2 models, entity and acl,
acl rules can be included/excluded and target is reference to entity ( or special case 'public' )
ACL:
const { DataTypes, Model } = require('sequelize');
class ACL extends Model {}
module.exports = (sequelize) => {
const attributes = {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
object_unique_id: {
type: DataTypes.STRING(36),
allowNull: false,
},
principal_unique_id: {
type: DataTypes.STRING(36),
allowNull: false,
},
rule: {
type: DataTypes.INTEGER(11),
allowNull: false,
defaultValue: 1,
comment: '1=allow, 0=deny',
},
};
const options = {
modelName: 'acl',
tableName: 'acl',
sequelize, // We need to pass the connection instance
};
return ACL.init(attributes, options);
};
ENTITY:
const { DataTypes, Model } = require('sequelize');
const { Op } = require('sequelize');
class Entity extends Model {}
module.exports = (sequelize, ACL) => {
Entity.init(
{
id: {
type: DataTypes.INTEGER(11).UNSIGNED,
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
unique_id: {
type: DataTypes.STRING(36),
allowNull: false,
},
name: {
type: DataTypes.STRING(50),
allowNull: false,
},
},
{
indexes: [
{
name: 'unique_id',
unique: true,
fields: ['unique_id'],
},
],
tableName: 'entity',
sequelize,
modelName: 'entity',
scopes: {
byPrincipalUID(principalUID) {
const includedCondition = [
{ principal_unique_id: 'public' },
];
if (principalUID) {
includedCondition.push({
principal_unique_id: principalUID,
});
}
return {
include: [
{
model: ACL,
where: {
[Op.and]: [
{ rule: 1 },
{ [Op.or]: includedCondition },
],
},
},
],
};
},
public: {
include: [
{
model: ACL,
where: {
[Op.and]: [
{ rule: 1 },
{ principal_unique_id: 'public' },
],
},
},
],
},
},
}
);
Entity.hasMany(ACL, {
sourceKey: 'unique_id',
foreignKey: 'object_unique_id',
});
return Entity;
};
test cases:
describe('AclService', () => {
it('should works with scopes', async () => {
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('sqlite::memory:');
const ACL = require('../db/models/acl.model')(sequelize);
const Entity = require('../db/models/entity.model')(sequelize, ACL);
await ACL.sync();
await Entity.sync();
await Entity.create({ name: 'test 1', unique_id: 's1' });
await Entity.create({ name: 'test 2', unique_id: 's2' });
await Entity.create({ name: 'test 3', unique_id: 's3' });
await ACL.create({
object_unique_id: 's1',
rule: 1,
principal_unique_id: 'public',
});
await ACL.create({
object_unique_id: 's2',
rule: 1,
principal_unique_id: 'c1',
});
await ACL.create({
object_unique_id: 's3',
rule: 1,
principal_unique_id: 'p1',
});
const all = await Entity.findAll();
expect(all.length).toBe(3);
const publicSubjects = await Entity.scope('public').findAll();
expect(publicSubjects.length).toBe(1);
const companySubjects = await Entity.scope({
method: ['byPrincipalUID', 'c1'],
}).findAll();
expect(companySubjects.length).toBe(2);
const accountSubjects = await Entity.scope({
method: ['byPrincipalUID', 'p1'],
}).findAll();
expect(accountSubjects.length).toBe(2);
});
it('should works with scopes and deny rule', async () => {
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('sqlite::memory:');
const ACL = require('../db/models/acl.model')(sequelize);
const Entity = require('../db/models/entity.model')(sequelize, ACL);
await ACL.sync();
await Entity.sync();
await Entity.create({ name: 'test 1', unique_id: 's1' });
await Entity.create({ name: 'test 2', unique_id: 's2' });
await ACL.create({
object_unique_id: 's1',
rule: 1,
principal_unique_id: 'public',
});
await ACL.create({
object_unique_id: 's2',
rule: 1,
principal_unique_id: 'public',
});
await ACL.create({
object_unique_id: 's2',
rule: 0,
principal_unique_id: 'c1',
});
const all = await Entity.findAll();
expect(all.length).toBe(2);
const publicSubjects = await Entity.scope('public').findAll();
expect(publicSubjects.length).toBe(2);
//s2 is denied for c1
const companySubjects = await Entity.scope({
method: ['byPrincipalUID', 'c1'],
}).findAll();
expect(companySubjects.length).toBe(1);
});
});
so with 'Grant' permission all works as expected.
But have no good ideas how to exclude 'Deny' records.
So in second test I have 2 'public' entities, but second one have "deny" rule for c1
I have only one idea, somehow use raw subquery something like
NOT EXISTS(SELECT id FROM acl
WHERE acl.object_unique_id = ${targetTable}.unique_id
AND (acl.rule = 0 AND (
.....
)
)
but not sure how to make it using sequelize

why isnt vue-chartjs receiving data from api?

I don't understand my console log is printing all the data. Do i have to return the data to something for the data to update on the chart? Maybe its something with nuxt? I have tried async mounted and async fetch with the same result. I have tried putting a $ infront of this.$chartData.
<script>
import { Pie } from 'vue-chartjs/legacy'
import { Chart as ChartJS, Title, Tooltip, Legend, ArcElement, CategoryScale } from 'chart.js'
import EthplorerService from '../../services/EthplorerService'
import CoinGeckoService from '../../services/CoinGeckoService'
ChartJS.register(Title, Tooltip, Legend, ArcElement, CategoryScale)
export default {
name: 'PieChart',
components: {
Pie,
},
data() {
return {
chartData: {
labels: [],
datasets: [
{
data: [],
backgroundColor: ['#0074D9', '#FF4136', '#2ECC40', '#39CCCC', '#01FF70', '#85144b', '#F012BE', '#3D9970', '#111111', '#AAAAAA'],
},
],
},
chartOptions: {
responsive: true,
maintainAspectRatio: false,
},
}
},
async created() {
const limit = 10
try {
this.loading = true
const coinData = await CoinGeckoService.getCoinData('chainlink')
const contractAddress = coinData.data.platforms.ethereum
const { data } = await EthplorerService.getTopTokenHolders(contractAddress, limit)
console.log(data.holders.map((x) => x.address))
console.log(data.holders.map((x) => x.share))
this.chartData.labels = data.holders.map((x) => x.address)
this.chartData.datasets.data = data.holders.map((x) => x.share)
this.loading = false
return this.chartData
} catch (e) {
this.loading = false
console.log(e)
}
},
}
</script>
Turns out i was missing the array position [0]. And I was missing the v-if.
this.chartData.datasets[0].data = data.holders.map((x) => x.share)
Followed the examples here and here
<template>
<Pie
v-if="!loading"
:chart-options="chartOptions"
:chart-data="chartData"
:chart-id="chartId"
:dataset-id-key="datasetIdKey"
:plugins="plugins"
:css-classes="cssClasses"
:styles="styles"
:width="width"
:height="height"
/>
</template>
<script>
import { Pie } from 'vue-chartjs/legacy'
import { Chart as ChartJS, Title, Tooltip, Legend, ArcElement, CategoryScale } from 'chart.js'
import EthplorerService from '../../services/EthplorerService'
import CoinGeckoService from '../../services/CoinGeckoService'
ChartJS.register(Title, Tooltip, Legend, ArcElement, CategoryScale)
export default {
name: 'PieChart',
components: {
Pie,
},
props: {
chartId: {
type: String,
default: 'pie-chart',
},
datasetIdKey: {
type: String,
default: 'label',
},
width: {
type: Number,
default: 400,
},
height: {
type: Number,
default: 400,
},
cssClasses: {
default: '',
type: String,
},
styles: {
type: Object,
default: () => {},
},
plugins: {
type: Array,
default: () => [],
},
},
data() {
return {
loading: true,
chartData: {
labels: [],
datasets: [
{
data: [],
backgroundColor: ['#0074D9', '#FF4136', '#2ECC40', '#39CCCC', '#01FF70', '#85144b', '#F012BE', '#3D9970', '#111111', '#AAAAAA'],
},
],
},
chartOptions: {
responsive: true,
maintainAspectRatio: false,
},
}
},
async mounted() {
const limit = 10
try {
this.loading = true
const coinData = await CoinGeckoService.getCoinData('chainlink')
const contractAddress = coinData.data.platforms.ethereum
const { data } = await EthplorerService.getTopTokenHolders(contractAddress, limit)
console.log(data.holders.map((x) => x.address.slice(1, 5)))
console.log(data.holders.map((x) => x.share))
this.chartData.labels = data.holders.map((x) => x.address.slice(2, 7))
this.chartData.datasets[0].data = data.holders.map((x) => x.share)
this.loading = false
} catch (e) {
this.loading = false
console.log(e)
}
},
}
</script>

Vue + Vuetify + Axios + Django : CRUD data table

I am trying to build a Vuetify CRUD using AXIOS. I am able to do CRUD operations, but am not able to display the newly added data till the page is refreshed. When I select edit, I am not able to see the existing data while editing. The editable dialog box shows empty.
Please help me if to resolve this.
Here is my script
import Navbar from '../components/Navbar.vue'
import { getAPI } from '../axios-api'
// import DataService from "../services/DataService";
export default {
data: () => ({
dialog: false,
dialogDelete: false,
headers: [
{ text: 'ID', align: 'start', value: 'id',},
{ text: 'Length', value: 'size' },
{ text: 'Weight', value: 'weight' },
{ text: 'Actions', value: 'actions', sortable: false },
],
info: [],
editedIndex: -1,
editedItem: {
ID: '',
Weight: 0,
Length: 0,
},
defaultItem: {
name: '',
Weight: 0,
Length: 0,
},
}),
components:{
Navbar
},
computed: {
formTitle () {
return this.editedIndex === -1 ? 'New Item' : 'Edit Item'
},
},
methods: {
initialize () {
getAPI.get('calibration/sizeweight')
.then(response => {
this.info = response.data
})
},
editItem (item) {
this.editedIndex = this.info.indexOf(item)
this.editedItem = Object.assign({}, item)
this.dialog = true
},
deleteItem (item) {
this.editedIndex = this.info.indexOf(item)
this.editedItem = Object.assign({}, item)
this.dialogDelete = true
},
deleteItemConfirm () {
this.info.splice(this.editedIndex, 1)
this.closeDelete()
getAPI.delete('calibration/sizeweight/'+this.editedItem.id)
.then(response=>{
console.log(response)
})
},
close () {
this.dialog = false
this.$nextTick(() => {
this.editedItem = Object.assign({}, this.defaultItem)
this.editedIndex = -1
})
},
closeDelete () {
this.dialogDelete = false
this.$nextTick(() => {
this.editedItem = Object.assign({}, this.defaultItem)
this.editedIndex = -1
})
},
save () {
if (this.editedIndex > -1) {
Object.assign(this.info[this.editedIndex], this.editedItem)
getAPI.put('calibration/sizeweight/'+this.editedItem.ID,{id:this.editedItem.ID ,weight:this.editedItem.Weight,size:this.editedItem.Length})
.then(response=>{
console.log(response)
this.initialize()
})
} else {
this.info.push(this.editedItem)
getAPI.post('calibration/sizeweight',{id:this.editedItem.ID ,weight:this.editedItem.Weight,size:this.editedItem.Length})
.then(response=>{
console.log(response)
this.initialize()
})
.catch(error => { console.log(error.response.data)})
}
this.close()
},
},
watch: {
dialog (val) {
val || this.close()
},
dialogDelete (val) {
val || this.closeDelete()
},
},
created () {
this.initialize()
},
}
</script>

Nuxt PM2 CPU up to 100%

Hello guys can you help me please!
My app use up to 100% CPU when a lot of users go to my app.
I tried a lot of things, and my config turned into a mess
This is my nuxt.config.ts.
import type { NuxtConfig } from '#nuxt/types';
const isDev = process.env.NODE_ENV !== 'production';
const mainConfig: NuxtConfig = {
...
build: {
cache: true,
optimization: {
minimize: true,
runtimeChunk: true,
concatenateModules: true,
splitChunks: {
chunks: 'all',
minSize: 30000,
maxSize: 0,
minChunks: 1,
maxAsyncRequests: 20,
maxInitialRequests: 3,
automaticNameDelimiter: '~',
name: true,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
chunks: 'all'
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
}
},
filenames: {
app: ({ isDev }) => (isDev ? '[name].js' : 'js/[name]/[contenthash].js'),
chunk: ({ isDev }) => (isDev ? '[name].js' : 'js/[name]/[contenthash].js'),
css: ({ isDev }) => (isDev ? '[name].css' : 'css/[contenthash].css'),
img: ({ isDev }) => (isDev ? '[path][name].[ext]' : 'img/[contenthash:7].[ext]'),
font: ({ isDev }) => (isDev ? '[path][name].[ext]' : 'fonts/[contenthash:7].[ext]')
},
extend(config, { isClient }) {
config.externals = [
function (context, request, callback) {
if (/(pdfmake)/.test(request) || /(xlsx)/.test(request)) {
return callback(null, 'commonjs ' + request);
}
callback();
}
];
}
},
router: { ... },
modules: [ ... ],
server: { ... },
watchers: {
webpack: {
ignored: ['**/node_modules', 'node_modules']
}
}
};
export default mainConfig;
The application does not stand up to 2000 users and breaks,
I really dont know what to do! :(
Maybe you will can help me?

Get data in ag-grid

I was able to pull data into the database with bootstrap-vue.
I need to transfer to ag-grid, but I don't know how to do it
Someone help-me, this is code in ag-grid:
<template v-if="instituicao">
<div>
<button #click="getSelectedRows()">Get Selected Rows</button>
<ag-grid-vue style="width: 1000px; height: 500px;"
class="ag-theme-balham"
v-model="instituicao.codigo" required
:floatingFilter="true"
:gridReady="onGridReady"
:enableColResize="true"
:columnDefs="columnDefs"
:rowData="rowData"
:enableSorting="true"
:enableFilter="true">
</ag-grid-vue>
</div>
</template>
<script>
import PageTitle from '../template/PageTitle'
import axios from 'axios'
import { baseApiUrl, showError } from '#/global'
import { AgGridVue } from "ag-grid-vue"
import { transformHeader, transformRows } from '../../lib/grid.js'
/* import "ag-grid-enterprise" */
export default {
name: 'InstituicaoAdmin',
components: { AgGridVue, PageTitle },
data() {
return {
columnDefs: null,
rowData: null,
mode: 'save',
instituicao: {},
instituicoes: [],
fields: [
{ key: 'id', label: 'Id', sortable: true },
{ key: 'name', label: 'Name', sortable: true }
],
}
},
methods: {
onGridReady(params) {
this.gridApi = params.api;
this.columnApi = params.columnApi;
this.gridApi.setHeaderHeight(50);
},
sizeToFit() {
this.gridApi.sizeColumnsToFit();
// this.autosizeHeaders();
},
autoSizeAll() {
var allColumnIds = [];
this.columnApi.getAllColumns().forEach(function(column) {
allColumnIds.push(column.colId);
});
this.columnApi.autoSizeColumns(allColumnIds);
},
getSelectedRows() {
const selectedNodes = this.gridApi.getSelectedNodes();
const selectedData = selectedNodes.map(node => node.data);
const selectedDataStringPresentation = selectedData.map(node => node.make + ' ' + node.model).join(', ');
alert(`Selected nodes: ${selectedDataStringPresentation}`);
},
loadInstituicoes() {
const url = `${baseApiUrl}/instituicao`
axios.get(url).then(res => {
this.instituicoes = res.data
})
},
reset() {
this.mode = 'save'
this.instituicao = {}
this.loadInstituicoes()
},
save() {
const method = this.instituicao.id ? 'put' : 'post'
const id = this.instituicao.id ? `/${this.instituicao.id}` : ''
axios[method](`${baseApiUrl}/instituicao${id}`, this.instituicao)
.then(() => {
this.$toasted.global.defaultSuccess()
this.reset()
})
.catch(showError)
},
remove() {
const id = this.instituicao.id
axios.delete(`${baseApiUrl}/instituicao/${id}`)
.then(() => {
this.$toasted.global.defaultSuccess()
this.reset()
})
.catch(showError)
},
loadInstituicao(instituicao, mode = 'save') {
this.mode = mode
this.instituicao = { ...instituicao }
}
},
beforeMount() {
this.columnDefs = [
{headerName: 'Id', field: 'id', sortable: true },
{headerName: 'Name', field: 'name', sortable: true, filter: true },
{headerName: 'Price', field: 'price', sortable: true, filter: true }
];
fetch('https://api.myjson.com/bins/15psn9')
.then(result => result.json())
.then(rowData => this.rowData = rowData);
},
computed: {
columnDefs() {
return transformHeader(this.payload.header);
},
rowData() {
return transformRows(this.payload.data.rows, this.columnDefs);
}
},
mounted() {
this.loadInstituicoes()
}
}
</script>
<style>
#import "../../../node_modules/ag-grid/dist/styles/ag-grid.css";
#import "../../../node_modules/ag-grid/dist/styles/ag-theme-balham.css";
</style>
My question is how can I do the GET, PUT, POST, and DELETE operations using the ag-grid framework.
Usando o bootstrap-vue, eu poderia executar ou obter o banco de dados através da propriedade "fields".
<script>
import PageTitle from '../template/PageTitle'
import axios from 'axios'
import { baseApiUrl, showError } from '#/global'
export default {
name: 'InstituicaoAdmin',
components: { PageTitle },
data: function() {
return {
mode: 'save',
instituicao: {},
instituicoes: [],
fields: [
{ key: 'id', label: 'Id', sortable: true },
{ key: 'name', label: 'Name', sortable: true }
]
}
},
methods: {
loadInstituicoes() {
const url = `${baseApiUrl}/instituicao`
axios.get(url).then(res => {
this.instituicoes = res.data
})
},
reset() {
this.mode = 'save'
this.instituicao = {}
this.loadInstituicoes()
},
save() {
const method = this.instituicao.id ? 'put' : 'post'
const id = this.instituicao.id ? `/${this.instituicao.id}` : ''
axios[method](`${baseApiUrl}/instituicao${id}`, this.instituicao)
.then(() => {
this.$toasted.global.defaultSuccess()
this.reset()
})
.catch(showError)
},
remove() {
const id = this.instituicao.id
axios.delete(`${baseApiUrl}/instituicao/${id}`)
.then(() => {
this.$toasted.global.defaultSuccess()
this.reset()
})
.catch(showError)
},
loadInstituicao(instituicao, mode = 'save') {
this.mode = mode
this.instituicao = { ...instituicao }
}
},
mounted() {
this.loadInstituicoes()
}
}
</script>
I was able to solve the problem using axios using destructuring:
beforeMount() {
this.columnDefs = [
{headerName: 'Id', field: 'id', editable: true},
{headerName: 'Name', field: 'name', editable: true}
];
axios.get(`${baseApiUrl}/instituicao`)
.then(({data}) => this.rowData = data)
},