diff --git a/deleteDevice/deleteDevice.ts b/deleteDevice/deleteDevice.ts new file mode 100644 index 0000000..5c9ab75 --- /dev/null +++ b/deleteDevice/deleteDevice.ts @@ -0,0 +1,41 @@ +import { AzureFunction, Context, HttpRequest } from '@azure/functions' +import { Registry } from 'azure-iothub' +import { r } from '../lib/http' +import { ErrorInfo, ErrorType, toStatusCode } from '../lib/ErrorInfo' + +const connectionString = process.env.IOT_HUB_CONNECTION_STRING || '' + +const deleteDevice: AzureFunction = async ( + context: Context, + req: HttpRequest, +): Promise => { + context.log({ req: JSON.stringify(req) }) + try { + const registry = Registry.fromConnectionString(connectionString) + const devices = registry.createQuery( + `SELECT * FROM devices WHERE deviceId='${req.params.id}'`, + ) + const res = await devices.nextAsTwin() + if (res.result.length === 0) { + context.res = r( + { + type: ErrorType.EntityNotFound, + message: `Device ${req.params.id} not found!`, + } as ErrorInfo, + toStatusCode[ErrorType.EntityNotFound], + ) + } else { + await registry.delete(req.params.id) + context.res = r({ success: true }) + } + } catch (error) { + context.log( + JSON.stringify({ + error: error.message, + }), + ) + context.res = r(error, 500) + } +} + +export default deleteDevice diff --git a/deleteDevice/function.json b/deleteDevice/function.json new file mode 100644 index 0000000..e77d797 --- /dev/null +++ b/deleteDevice/function.json @@ -0,0 +1,18 @@ +{ + "bindings": [ + { + "authLevel": "anonymous", + "type": "httpTrigger", + "direction": "in", + "name": "req", + "methods": ["delete"], + "route": "device/{id}" + }, + { + "type": "http", + "direction": "out", + "name": "res" + } + ], + "scriptFile": "../dist/deleteDevice/deleteDevice.js" +} diff --git a/getDevice/getDevice.ts b/getDevice/getDevice.ts index 477b52f..a8874ca 100644 --- a/getDevice/getDevice.ts +++ b/getDevice/getDevice.ts @@ -28,6 +28,11 @@ const getDevice: AzureFunction = async ( context.res = r(res.result[0]) } } catch (error) { + context.log( + JSON.stringify({ + error: error.message, + }), + ) context.res = r(error, 500) } } diff --git a/listDevices/listDevices.ts b/listDevices/listDevices.ts index e531626..7864df0 100644 --- a/listDevices/listDevices.ts +++ b/listDevices/listDevices.ts @@ -17,6 +17,11 @@ const listDevices: AzureFunction = async ( const res = await devices.nextAsTwin() context.res = r(res.result) } catch (error) { + context.log( + JSON.stringify({ + error: error.message, + }), + ) context.res = r(error, 500) } } diff --git a/updateDevice/updateDevice.ts b/updateDevice/updateDevice.ts index 6ed32c5..a57eea4 100644 --- a/updateDevice/updateDevice.ts +++ b/updateDevice/updateDevice.ts @@ -35,6 +35,11 @@ const updateDevice: AzureFunction = async ( context.res = r(true) } } catch (error) { + context.log( + JSON.stringify({ + error: error.message, + }), + ) context.res = r(error, 500) } }