Database transaction

Run multiple sql queries wrapped in database transaction

Lets insert order with items as a single database transaction

create table `order`
(
    id         varchar(40) charset utf8mb3                                not null
        primary key,
    amount     int                                                        not null,
    user_id    int                                                        not null,
    status     enum ('new', 'paid', 'returned') default 'new'             not null,
    created_at timestamp                        default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP,
    constraint order_user_id_fk
        foreign key (user_id) references user (id)
);
create table order_item
(
    id         int auto_increment
        primary key,
    order_id   varchar(40)   not null,
    product_id int           not null,
    quantity   int default 0 not null,
    constraint order_item__product_fk
        foreign key (product_id) references product (id),
    constraint order_item_order_id_fk
        foreign key (order_id) references `order` (id)
)
    charset = utf8mb3;
{
  "path": "/api/orders",
  "methods": [
    "POST"
  ],
  "query": "order-new",
  "authorized": true
}
{
  "type": "javascript",
  "id": "order-new",
  "file": "order-new.js",
  "public": true,
  "params": []
}
let orderId = uuid(),
    currentTransaction = transaction("sample-database-connection"),
    orderData = null;

try {
    orderData = currentTransaction.run("orders-insert", {
        "id": orderId,
        "amount": totalPrice,
        "currentUserId": 1,
    }).Data

    currentTransaction.run("order-item-insert", {
        "orderId": orderData.id,
        "productId": 1,
        "quantity": 1
    })

    currentTransaction.run("order-item-insert", {
        "orderId": orderData.id,
        "productId": 2,
        "quantity": 22
    })

    currentTransaction.commit()
} catch (e) {
    currentTransaction.rollback()
    throw {"error": e}
}

setStatusCode(200)
setResult({
    orderId: orderData.id
})
{
  "orderId": "01ce6540-cdbf-43c7-8def-3abc45147e3b"
}

You could improve logic by sending extra parameters like product ids or perform more any complex business logic

Last modified April 16, 2024: content fix (a2d9b96)