Last active
February 4, 2019 12:01
-
-
Save Jojoooo1/bc6bc6c977c618e6263ae2a5797a72ec to your computer and use it in GitHub Desktop.
code-2.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import uuidv4 from 'uuid/v4'; | |
// import { performance } from 'perf_hooks'; | |
import { generateCodigo } from '../utils'; | |
import { usarCodigoSchema } from '../models/codigo'; | |
// { descend into nested schema, return on first error, remove unspecified keys from objects } | |
const validationOptions = { recursive: true, abortEarly: true, stripUnknown: true }; | |
// [...] | |
export const usarCodigo = async (stub, args) => { | |
let data; | |
let formattedData; | |
// 1. Parses JSON stringified request | |
try { | |
data = JSON.parse(args.toString()); | |
} catch (err) { | |
throw new Error('Não foi possivel decodificar o JSON, por favor verifique o formato'); | |
} | |
console.info('--- start usarCodigo ---'); | |
// 2. Verifies Object format | |
try { | |
formattedData = await usarCodigoSchema.validate(data, validationOptions); | |
} catch (err) { | |
// log yup validation errors | |
console.log(err); | |
throw new Error(err.message); | |
} | |
const dataAsBytes = await stub.getState(data.id); | |
// 3. Verifies if data already exist | |
if (!dataAsBytes.toString()) { | |
throw new Error(`codigo "${data.id}" nao encontrado`); | |
} | |
// 4. Parses data that will be updated | |
const dataToUpdate = JSON.parse(dataAsBytes.toString()); | |
// Verify if codigo was not already used | |
if (dataToUpdate.usado) { | |
throw new Error(`codigo "${data.id}" ja usado`); | |
} | |
// 5. Merges formatted data | |
const updatedData = { ...dataToUpdate, ...formattedData }; | |
// 6. Transforms the JSON data into Bytes data | |
const updatedDataAsBytes = Buffer.from(JSON.stringify(updatedData)); | |
// 7. Pushes updated data into the ledger | |
await stub.putState(updatedData.id, updatedDataAsBytes); | |
// 8. Creates event | |
stub.setEvent('codigoUsado', updatedDataAsBytes); | |
console.info('=================='); | |
console.log(updatedData); | |
console.info('=================='); | |
console.info('--- usarCodigo ---'); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment