Skip to content

Commit

Permalink
Merge pull request particle-iot#33 from AntonPuko/dev
Browse files Browse the repository at this point in the history
clean up / device rename
  • Loading branch information
jlkalberer committed Dec 12, 2016
2 parents e75ef89 + 9fc4e0f commit 22eaf12
Show file tree
Hide file tree
Showing 8 changed files with 95 additions and 73 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
"express": "^4.14.0",
"express-oauth-server": "^2.0.0-b1",
"moment": "*",
"moniker": "^0.1.2",
"morgan": "^1.7.0",
"request": "*",
"spark-protocol": "../spark-protocol",
Expand Down
8 changes: 0 additions & 8 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,16 +81,8 @@ export default (settings: Settings, deviceServer: Object): $Application => {
settings,
);

// TODO wny do we need next line? (Anton Puko)
eventsV1.loadViews(app);
api.loadViews(app);

const noRouteMiddleware: Middleware = (
request: $Request,
response: $Response,
): mixed => response.sendStatus(404);

app.use(noRouteMiddleware);

return app;
};
4 changes: 4 additions & 0 deletions src/lib/RouteConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,4 +103,8 @@ export default (
});
});
});

app.all('*', (request: $Request, response: $Response): void =>
response.sendStatus(404),
);
};
20 changes: 7 additions & 13 deletions src/lib/controllers/Controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,16 @@ import type { User } from '../../types';
import type { HttpResult } from './types';

export default class Controller {
user: User;
request: $Request;
response: $Response;
bad(message: string, status: number = 400) {
return {
data: {
error: message,
ok: false,
},
status: status,
};
}
user: User;

bad = (message: string): HttpResult<*> => ({
data: { message },
status: 400,
bad = (message: string, status: number = 400): HttpResult<*> => ({
data: {
error: message,
ok: false,
},
status,
});

ok = <TType>(output?: TType): HttpResult<TType> => ({
Expand Down
32 changes: 27 additions & 5 deletions src/lib/controllers/DevicesController__john.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// @flow

import type { Device, DeviceRepository } from '../../types';
import type { DeviceAPIType } from '../deviceToAPI';

import settings from '../../settings';
import Controller from './Controller';
import httpVerb from '../decorators/httpVerb';
import route from '../decorators/route';
Expand All @@ -19,11 +19,12 @@ class DevicesController extends Controller {

@httpVerb('get')
@route('/v1/devices')
async getDevices() {
async getDevices(): Promise<*> {
try {
const devices = await this._deviceRepository.getAll();

return this.ok(devices.map(device => deviceToAPI(device)));
return this.ok(devices.map((device: Device): DeviceAPIType =>
deviceToAPI(device)));
} catch (exception) {
// I wish we could return no devices found but meh :/
return this.ok([]);
Expand All @@ -32,7 +33,7 @@ class DevicesController extends Controller {

@httpVerb('get')
@route('/v1/devices/:deviceID')
async getDevice(deviceID: string) {
async getDevice(deviceID: string): Promise<*> {
try {
const device = await this._deviceRepository.getDetailsByID(deviceID);
return this.ok(deviceToAPI(device));
Expand All @@ -41,13 +42,34 @@ class DevicesController extends Controller {
}
}

@httpVerb('put')
@route('/v1/devices/:deviceID')
async updateDevice(deviceID: string, postBody: { name?: string }): Promise<*> {
try {
// 1 rename device
if (postBody.name) {
const updatedAttributes = this._deviceRepository.renameDevice(
deviceID,
postBody.name,
);

return this.ok({ name: updatedAttributes.name, ok: true });
}


return this.ok();
} catch (exception) {
return this.bad(exception);
}
}

@httpVerb('post')
@route('/v1/devices/:deviceID/:functionName')
async callDeviceFunction(
deviceID: string,
functionName: string,
postBody: Object,
) {
): Promise<*> {
try {
const result = await this._deviceRepository.callFunction(
deviceID,
Expand Down
9 changes: 4 additions & 5 deletions src/lib/controllers/ProvisioningController.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
// @flow

import type { Device, DeviceRepository } from '../../types';
import type { DeviceRepository } from '../../types';

import settings from '../../settings';
import Controller from './Controller';
import httpVerb from '../decorators/httpVerb';
import route from '../decorators/route';
Expand All @@ -21,12 +20,12 @@ class ProvisioningController extends Controller {
@route('/v1/provisioning/:coreID')
async provision(
coreID: string,
postBody: {publicKey: string},
) {
postBody: { publicKey: string },
): Promise<*> {
try {
const device = await this._deviceRepository.provision(
coreID,
'UserIDGoesHere',
this.user.id,
postBody.publicKey,
);

Expand Down
5 changes: 4 additions & 1 deletion src/lib/controllers/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ export type HttpResult<TType> = {
data: ?TType,
status: number,
} | {
data: ?string,
data: {
error: string,
ok: false,
},
status: number,
};
89 changes: 48 additions & 41 deletions src/lib/repository/DeviceRepository__john.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class DeviceRepository {
this._deviceServer = deviceServer;
}

async getByID(deviceID: string): Promise<Device> {
getByID = async (deviceID: string): Promise<Device> => {
const attributes = await this._deviceAttributeRepository.getById(deviceID);
const core = this._deviceServer.getCore(attributes.deviceID);
// TODO: Not sure if this should actually be the core ID that gets sent
Expand All @@ -45,33 +45,31 @@ class DeviceRepository {
lastFlashedAppName: null,
lastHeard: response.lastPing,
};
}
};

async getDetailsByID(deviceID: string): Promise<Device> {
getDetailsByID = async (deviceID: string): Promise<Device> => {
const core = this._deviceServer.getCore(deviceID);
if (!core) {
throw 'Could not get device for ID';
throw new Error('Could not get device for ID');
}

return Promise.all([
this._deviceAttributeRepository.getById(deviceID),
core.onApiMessage(
deviceID,
{ cmd: "Describe" },
)
]).then(([attributes, description]) => {
return {
...attributes,
connected: true,
lastFlashedAppName: null,
lastHeard: new Date(),
functions: description.f,
variables: description.v,
};
})
deviceID,
{ cmd: 'Describe' },
),
]).then(([attributes, description]): Device => ({
...attributes,
connected: true,
functions: description.f,
lastFlashedAppName: null,
lastHeard: new Date(),
variables: description.v,
}));
};

}
async getAll(): Promise<Array<Device>> {
getAll = async (): Promise<Array<Device>> => {
const devicesAttributes = await this._deviceAttributeRepository.getAll();
const devicePromises = devicesAttributes.map(async attributes => {
const core = this._deviceServer.getCore(attributes.deviceID);
Expand All @@ -96,62 +94,71 @@ class DeviceRepository {
});

return Promise.all(devicePromises);
}
};

async callFunction(
callFunction= async (
deviceID: string,
functionName: string,
functionArguments: Object,
): Promise<*> {
): Promise<*> => {
const core = this._deviceServer.getCore(deviceID);
if (!core) {
return null;
}

console.log(functionArguments);
const result = await core.onApiMessage(
deviceID,
{ cmd:'CallFn', name: functionName, args: functionArguments },
{ cmd: 'CallFn', name: functionName, args: functionArguments },
);

if (result.error) {
throw result.error;
}

return result.result;
}
};

async provision(
provision = async (
deviceID: string,
userID: string,
publicKey: string,
): Promise<*> {
if (!deviceID) {
throw 'No deviceID provided';
}

try {
const createdKey = ursa.createPublicKey(publicKey);
if (!publicKey || !ursa.isPublicKey(createdKey)) {
throw 'No key provided';
}
} catch (exception) {
logger.error('error while parsing publicKey', exception);
throw 'Key error ' + exception;
}
): Promise<*> => {
if (!deviceID) {
throw new Error('No deviceID provided');
}

try {
const createdKey = ursa.createPublicKey(publicKey);
if (!publicKey || !ursa.isPublicKey(createdKey)) {
throw new Error('No key provided');
}
} catch (exception) {
logger.error('error while parsing publicKey', exception);
throw new Error(`Key error ${exception}`);
}
this._deviceKeyRepository.update(deviceID, publicKey);
const existingAttributes = this._deviceAttributeRepository.getById(
deviceID,
);
const attributes = {
deviceID,
name: NAME_GENERATOR.choose(),
deviceID: deviceID,
...existingAttributes,
registrar: userID,
timestamp: new Date(),
};
this._deviceAttributeRepository.update(attributes);

return await this.getByID(deviceID);
};

renameDevice = (deviceID: string, name: string): DeviceAttributes => {
const attributes = this._deviceAttributeRepository.getById(deviceID);
const attributesToSave = {
...attributes,
name,
};
return this._deviceAttributeRepository.update(attributesToSave);
}
}

Expand Down

0 comments on commit 22eaf12

Please sign in to comment.