1.0.3 • Published 2 years ago

pglock-v2 v1.0.3

Weekly downloads
-
License
ISC
Repository
github
Last release
2 years ago

PG Lock

Description

參考 colonist4/pg-mutex-lock 完善 postgres 諮詢鎖功能,並使用 pg pool 解決斷線自動重連 Refer to colonist4/pg-mutex-lock to improve postgres advisory lock function, and use pg pool to solve disconnection and automatic reconnection

Feature

  • Support multi-process mutex lock
  • Support single-process mutex lock
  • Support retry, timeout configuration
  • Full typescript support
  • Support pg pool

API

class PGLock

This class is entry point of features. All functions are located under this class instance.

Options

NameTypeRequiredDefaultDescription
poolPoolnoundefineduse other pg pool (Create if empty)
poolConfigPoolConfigyesundefinedrefer to PoolConfig
timeoutnumberno10 * 1000acquire lock timeout
retryCountnumberno3acquire lock retry count

Method acquireLock (client: PoolClient, key: string) : Promise\<boolean>

Try to acquire lock for given key. If success, will be resolved with true. If failed, will be rejected.

Method releaseLock (client: PoolClient, key: string) : Promise\<boolean>

Try to release lock for given key. It directly return results of pg_advisory_unlock.

Method lock (key: string, func: () => Promise\<any>) : Promise\<any>

Mutex lock by async function.

Example

import { PGLock } from 'pglock-v2'

const pgLock = new PGLock({
  poolConfig: {
    host: 'localhost',
    port: 5432,
    user: 'postgres',
    password: 'password',
    database: 'database',
  },
})

setTimeout(async () => {
  console.log('start A')
  await pgLock.lock('test', async () => {
    console.log('locked A')
    await wait(1000)
    console.log('unlocked A')
  })
}, 100)

setTimeout(async () => {
  console.log('start B')
  await pgLock.lock('test', async () => {
    console.log('locked B')
    await wait(100)
    console.log('unlocked B')
  })
}, 300)

Dependencies

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago