Last active
March 8, 2023 05:05
-
-
Save pphetra/288b202ba5800b364fb34c531485280a to your computer and use it in GitHub Desktop.
test_optimistic_lock
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
/** @format */ | |
describe("AppService", () => { | |
const client = new PrismaClient({ | |
// log: ['query', 'info', 'warn'], | |
}); | |
afterAll(async () => { | |
await client.$disconnect(); | |
}); | |
beforeEach(async () => { | |
await client.$transaction(async (tx) => { | |
await tx.line.deleteMany(); | |
await tx.batch.deleteMany(); | |
await tx.product.deleteMany(); | |
}); | |
jest.setTimeout(60000); | |
}); | |
it("integration version: retry operation if optimistic lock detected", async () => { | |
const uow = new PrismaUnitOfWork(client); | |
await client.product.create({ | |
data: { | |
sku: "SMALL-TABLE", | |
batches: { | |
create: { | |
sku: "SMALL-TABLE", | |
ref: "batch-001", | |
qty: 20, | |
eta: new Date(), | |
}, | |
}, | |
}, | |
}); | |
const n = 20; | |
const services = []; | |
for (let i = 0; i < n; i++) { | |
const service = new AppService(`${i}`); | |
services.push(service); | |
} | |
let cnt = 0; | |
const tasks = services.map((service: AppService) => { | |
++cnt; | |
return service.allocate("test" + cnt, "SMALL-TABLE", 1, uow); | |
}); | |
await Promise.all(tasks); | |
const assertProduct = await uow.productRepository.get("SMALL-TABLE"); | |
const assertBatch = assertProduct.batches.find( | |
(b) => b.ref === "batch-001" | |
); | |
expect(assertBatch.allocatedQuantity).toBe(n); | |
}); | |
}); |
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
/** @format */ | |
return backOff( | |
() => | |
this.prisma.$transaction( | |
(tx) => { | |
return fn(new TxUow(tx)); | |
}, | |
{ | |
isolationLevel: "RepeatableRead", | |
} | |
), | |
{ | |
retry: (e) => { | |
console.log("error", e); | |
return e.code !== undefined; | |
// return e.code === 'P2025' || e.code === 'P2034'; | |
}, | |
numOfAttempts: 6, | |
jitter: "full", | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment