Writing Smart Contracts using Convector — a Fullstack JavaScript Framework

class Product extends ConvectorModel<Product> {
@ReadOnly()
@Required()
type = 'io.worldsibu.example.product';
@Required()
@Validate(yup.string())
name: string;
@Required()
@Validate(yup.number())
price: number;
@Required()
@Validate(yup.string())
owner: string;
@ReadOnly()
@Default(() => Date.now())
@Validate(yup.number())
created: number;
}
@Controller('product')
class ProductCtrl extends ConvectorController {
@Invokable()
async create(
@Param(Product) product: Product
) {
const _product = await Product.getOne(id);
if (product.id === _product.id) {
throw new Error('Product ID already created');
}
product.owner = this.sender; await product.save();
}
@Invokable()
async transfer(
@Param(yup.string()) id: string,
@Param(yup.string()) to: string
) {
const product = await Product.getOne(id);
if (product.owner !== this.sender) {
throw new Error('Only the owner can transfer the product');
}
product.owner = to; await product.save();
}
}
describe('ProductController' () => {
let adapter: MockControllerAdapter;
let productCtrl: ProductCtrl;
beforeEach(async () => {
adapter = new MockControllerAdapter();
productCtrl = new ProductCtrl(adapter);
await adapter.init([
{
version: '*',
controller: 'ProductCtrl',
name: '/path/to/controller-package'
}
]);
});
it('should create a product', async () => {
const productId = uuid();
await productCtrl.create(new Product({
id: productId,
name: 'OnePlus 6',
price 600
}));
const product = await adapter.getById<Product>(productId); expect(product).to.exist;
expect(product.name).to.eq('OnePlus 6');
});
});

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Diego Barahona

Diego Barahona

DevOps and Blockchain Architect and Consultant