Skip to content

Commit

Permalink
BE: aggiunte API per i devices - FE: aggiunto backe button nel form d…
Browse files Browse the repository at this point in the history
…ei tenant #10 #11
  • Loading branch information
mdslp committed Mar 26, 2020
1 parent 98f845e commit 5e2c372
Show file tree
Hide file tree
Showing 5 changed files with 205 additions and 51 deletions.
9 changes: 6 additions & 3 deletions backend/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,19 @@ require('./passport').setupStrategies(passport);
const pubApiDNSRoute = require('./routes/public/dnsRoutes');
const pubApiUserRoutes = require('./routes/public/userRoutes')(passport);

app.use('/dns', pubApiDNSRoute);
app.use('/user', pubApiUserRoutes);

const prvApiTenantRoute = require('./routes/private/tenantRoutes');
const prtApiUserRoutes = require('./routes/private/userRoutes');
const prtApiDeviceRoutes = require('./routes/private/deviceRoutes');

app.use('/dns', pubApiDNSRoute);
app.use('/user', pubApiUserRoutes);

app.use('/api/private/device', authenticate, prtApiDeviceRoutes);
app.use('/api/private/tenant', authenticate, prvApiTenantRoute);
app.use('/api/private/user', authenticate, prtApiUserRoutes);



const frontendPublic = path.join(__dirname, '../../frontend/public');
const frontendDist = path.join(__dirname, '../../frontend/dist');
app.use('/public', express.static(frontendPublic));
Expand Down
136 changes: 136 additions & 0 deletions backend/src/routes/private/deviceRoutes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import * as express from 'express';
import * as HttpStatus from 'http-status-codes';
import DeviceStore from '../../stores/deviceStore';

import { IDevice, ISearchOpt } from '../../interfaces/interfaces';
const _ = require('lodash');
const factory = require('../../shared/factory');
const router = express.Router();
const deviceStore = new DeviceStore();

router.get(
'/', async (
req: any,
res: express.Response,
next: express.NextFunction
) => {
const tenant_id = req.query.id;
try {
const deviceResponse = await deviceStore.findById(tenant_id);
if (deviceResponse && deviceResponse.length == 1) {
const device = deviceResponse[0];
const result = factory.generateSuccessResponse(device, null, "Device found");
res.status(HttpStatus.OK).send(result);
} else {
const result = factory.generateErrorResponse(null, null, "Device not found");
res.status(HttpStatus.NOT_FOUND).send(result);
}
} catch (error) {
const result = factory.generateErrorResponse(null, error, "ERROR");
res.status(HttpStatus.INTERNAL_SERVER_ERROR).send(result);
res.end();
}
return router;
}
);

router.get(
'/getAll', async (
req: express.Request,
res: express.Response,
next: express.NextFunction
) => {
try {
const options = req.query.options;
const search = req.query.search;
let searchOptions: ISearchOpt = options ? JSON.parse(options) : {};
searchOptions.itemsPerPage = searchOptions.itemsPerPage || 25;
searchOptions.activePage = searchOptions.activePage || 1;
searchOptions.needle = search || "";
const devicesRes = await deviceStore.getAll(searchOptions);


if (devicesRes && devicesRes.length > 0) {
const result = factory.generateSuccessResponse(
{devices: devicesRes, options: searchOptions},
null,
'Devices found'
);
res.status(HttpStatus.OK).json(result);
} else {
const result = factory.generateSuccessResponse(
null,
null,
'Devices not found'
);
res.status(HttpStatus.OK).json(result);
}
} catch (error) {
const result = factory.generateErrorResponse(
null,
error,
'Devices not found'
);
res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(result);
}
}
);

router.post('/create', async (req, res, next) => {
const device = req.body.params;
try {
const devices = await deviceStore.findBy(device);
let message = '';
if (!devices || devices.length == 0) {
const resCreation = await deviceStore.create(device);
if (resCreation && resCreation.length == 1) {
message = 'Device successfully created'
const result = factory.generateSuccessResponse(null, null, message);
res.status(HttpStatus.OK).json(result);
} else {
const result = factory.generateErrorResponse(null, null, 'Error');
res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(result);
}
} else {
message = 'Device already exists'
const result = factory.generateSuccessResponse(null, null, message);
res.status(HttpStatus.OK).json(result);
}
} catch (error) {
console.log("ERR", error);
const result = factory.generateErrorResponse(null, null, 'Error');
res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(result);
}
});

router.put('/update', async (req, res, next) => {
const device = req.body.params;
try {
if (!device.id) {
const result = factory.generateErrorResponse(null, null, 'Error');
res.status(HttpStatus.BAD_REQUEST).json(result);
}
const devices = await deviceStore.findById(device.id);
let message = '';
if (devices.length == 1) {
const resUpdate = await deviceStore.update(device);
if (resUpdate && resUpdate.length == 1) {
message = 'Device successfully updated'
const result = factory.generateSuccessResponse(null, null, message);
res.status(HttpStatus.OK).json(result);
} else {
const result = factory.generateErrorResponse(null, null, 'Error');
res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(result);
}
} else {
message = 'Device not found'
const result = factory.generateSuccessResponse(null, null, message);
res.status(HttpStatus.NOT_FOUND).json(result);
}
} catch (error) {
const result = factory.generateErrorResponse(null, null, 'Error');
res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(result);
}
});

module.exports = router;
1 change: 0 additions & 1 deletion backend/src/routes/private/tenantRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ router.get(
next: express.NextFunction
) => {
try {
console.log("req.query", req.query);
const options = req.query.options;
const search = req.query.search;
let searchOptions: ISearchOpt = options ? JSON.parse(options) : {};
Expand Down
18 changes: 17 additions & 1 deletion backend/src/stores/deviceStore.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { IDevice } from '../interfaces/interfaces';
import { IDevice, ISearchOpt } from '../interfaces/interfaces';
const _ = require('lodash');
const moment = require('moment');
var config = require('../../../backend/knexfile');
Expand Down Expand Up @@ -32,4 +32,20 @@ export default class DeviceStore {
findAll() {
return knex('devices').returning('*');
}

getAll(options: ISearchOpt) {
return knex.raw(`SELECT *
FROM devices
WHERE description LIKE '%${options.needle}%'
OR edge_interface_name LIKE '%${options.needle}%'
ORDER BY created_at DESC
LIMIT ${options.itemsPerPage}
OFFSET ${(options.itemsPerPage * (options.activePage - 1))}`
)
.then((data: any) => {
return data;
}).catch((err: any) => {
return err;
});
}
}
92 changes: 46 additions & 46 deletions frontend/src/components/forms/tenantForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import * as NotificationActions from '../../actions/notificationActions';
import * as UserActions from '../../actions/userActions';
import TenantApi from './../../api/tenantApi';
import DNSBaseComponent from '../dnsBaseComponent';
import { Grid, Input, Button, Container, Segment, Card, Image, Form } from 'semantic-ui-react';
import { Grid, Input, Button, Container, Segment, Card, Image, Form, Icon } from 'semantic-ui-react';
import { history } from '../../main';
import _ from 'lodash';
import { ITenant } from '../../../interfaces/tenant';
Expand All @@ -21,7 +21,6 @@ interface CompState {
edge_interface_name?: string;
}


class TenantForm extends DNSBaseComponent<CompProps | any, CompState> {
state = {
description: '',
Expand Down Expand Up @@ -85,51 +84,52 @@ class TenantForm extends DNSBaseComponent<CompProps | any, CompState> {

render() {
return (
<Segment raised>
<Card fluid centered>
<Card.Content>
<Card.Header className="headerHomePage">Create Tenant</Card.Header>
<Card.Description>

<Form size="small">
<Grid textAlign="center" className='loginForm'>
<Grid.Row width={12}>
<Input
placeholder="edge interface name"
name="edge_interface_name"
type="text"
value={this.state.edge_interface_name}
onChange={(event: any) => {
this.handleChange(event);
}}
/>
</Grid.Row>
<Grid.Row width={12}>
<Input
placeholder="description"
name="description"
type="text"
value={this.state.description}
onChange={(event: any) => {
this.handleChange(event);
}}
/>
</Grid.Row>

<Button
type='submit'
className="buttonLoginForm"
onClick={(event: any) => {
this.createTenant();
}}
>Crea
</Button>
</Grid>
</Form>
</Card.Description>
</Card.Content>
</Card>
<>
<Button floated='right' icon primary size='small' className="customButton"
onClick={() => {
history.push(`/home`);
}}>
<Icon name='arrow left' />
</Button>
<Segment raised>
Creazione Tenant
<Form size="small">
<Grid textAlign="center" className='loginForm'>
<Grid.Row width={12}>
<Input
placeholder="edge interface name"
name="edge_interface_name"
type="text"
value={this.state.edge_interface_name}
onChange={(event: any) => {
this.handleChange(event);
}}
/>
</Grid.Row>
<Grid.Row width={12}>
<Input
placeholder="description"
name="description"
type="text"
value={this.state.description}
onChange={(event: any) => {
this.handleChange(event);
}}
/>
</Grid.Row>

<Button
type='submit'
className="buttonLoginForm"
onClick={(event: any) => {
this.createTenant();
}}
>Crea
</Button>
</Grid>
</Form>
</Segment>
</>
);
}
}
Expand Down

0 comments on commit 5e2c372

Please sign in to comment.