Git Product home page Git Product logo

bs-knex's Introduction

[DEPRECATED] bs-knex

version downloads license

[DEPRECATED] - No longer being actively maintained

BuckleScript utilities for working with the Node knex library.

Installation

Install via Yarn or npm:

yarn add bs-knex

Add bs-knex to your bs-dependencies in bsconfig.json:

{
  "bs-dependencies": [
    "bs-knex"
  ]
}

Getting Started

To start working with Knex, first define a config:

let (to_opt, getWithDefault) = (Js.Nullable.to_opt, Js.Option.getWithDefault);

let connection =
  KnexConfig.Connection.make(
    ~user=Config.Database.username,
    ~password=Config.Database.password,
    ~host=Config.Database.hostname,
    ~port=Config.Database.port,
    ~database=Config.Database.name,
    ()
  );

let pool =
  KnexConfig.Pool.make(
    ~min=Config.Database.poolMin,
    ~max=Config.Database.poolMax,
    ~idleTimeoutMillis=Config.Database.poolIdle,
    ()
  );

let config =
  KnexConfig.make(~client="pg", ~connection, ~pool, ~acquireConnectionTimeout=2000, ());

Then you can initialize a client:

let knex = Knex.make(config);

You can now try a raw query to verify the connection:

knex |> Knex.raw("select now()")

Querying

Use the query builder to structure your request for the database:

Knex.(
  knex
  |> fromTable("users")
  |> where({"id": id})
  |> update({"first_name": firstName})
)

When you're ready to wait for results, call toPromise:

|> then_(
  (results) =>
    switch results {
    /* No user found, so resolve with None to signal onboarding */
    | [||] => resolve(None)
    | users => resolve(Some(users[0]))
    }
)

Handle empty results with the rejectIfAny handler:

|> then_(rejectIfEmpty(~error="Unable to update User with id: " ++ id))

Handle specific unique violations with the handleUniqueError utility:

|> KnexUtils.handleUniqueError(
  ~name="users_email_unique",
  ~message="That email address is already in use."
)
|> KnexUtils.handleUniqueError(
  ~name="users_user_name_unique",
  ~message="That user name is already in use."
)

Finish off your operation by handling any remaining generic database errors with KnexUtils:

|> KnexUtils.handleDbErrors

This handles a some common database error cases, which will hopefully grow over time as the library becomes more mature.

License

BSD 2-Clause

bs-knex's People

Contributors

bkonkle avatar glennsl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

bnoguchi glennsl c19

bs-knex's Issues

Unhandled Promise rejection when calling KnexUtils.handleUniqueError()

"bs-knex": "3.1.0"
"bs-platform": "4.0.7"
Node.js v10.15.0

I have the following javascript code in an entry point for a node app

process.on('unhandledRejection', (error, p) => {
  console.error('Unhandled Rejection at: Promise', p, 'error:', error);
});

When I call into Knex with something that looks like this with something that triggers the unique error

let insert = (owner: string, repo: string) =>
  Homn_Knex.knex
  |> Knex.fromTable("github_release")
  |> Knex.insert({"owner": owner, "repo": repo})
  |> Knex.toPromise
  |> KnexUtils.handleUniqueError(
       ~name="github_release_owner_repo_unique",
       ~message={j|The repository "$repo" already exists for "$owner"|j},
     )
  |> KnexUtils.handleDbErrors;

I get this console output (despite the rejection being handled later in the flow by reason-apollo)

Unhandled Rejection at: Promise Promise {
  <rejected> { error: duplicate key value violates unique constraint "github_release_owner_repo_unique"
      at Connection.parseE (/Users/wtf/src/homn-api-reason/node_modules/pg/lib/connection.js:554:11)
      at Connection.parseMessage (/Users/wtf/src/homn-api-reason/node_modules/pg/lib/connection.js:379:19)
      at Socket.<anonymous> (/Users/wtf/src/homn-api-reason/node_modules/pg/lib/connection.js:119:22)
      at Socket.emit (events.js:182:13)
      at addChunk (_stream_readable.js:283:12)
      at readableAddChunk (_stream_readable.js:264:11)
      at Socket.Readable.push (_stream_readable.js:219:10)
      at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)

This is being caused by the promise being rejected twice here?
https://github.com/bkonkle/bs-knex/blob/master/src/KnexUtils.re#L64
and
https://github.com/bkonkle/bs-knex/blob/master/src/KnexUtils.re#L73

I ended up writing my own handleUniqueError() and catchUniqueError() implementations in a module outside bs-knex which don't trigger the unhandled promise rejection.
Removed the let continue = reject(Debug.toExn(exn)); line and explicitly call Js.Promise.reject where it was used
I'm still learning Reason, is that the correct way to fix this, or am I potentially misunderstanding the error? This is what I came up with.

let catchUniqueError = (~name: string, ~handle, promise) =>
  Js.Nullable.(
    promise
    |> Js.Promise.catch(exn => {
         let codeOpt = exn |> KnexUtils.exnCode |> toOption;
         switch (codeOpt) {
         | Some(code) =>
           if (code === KnexUtils.uniqueViolation) {
             let constraintOpt = exn |> KnexUtils.exnConstraint |> toOption;
             switch (constraintOpt) {
             | Some(constraintName) =>
               if (constraintName === name) {
                 handle(exn);
               } else {
                 Js.Promise.reject(Debug.toExn(exn));
               }
             | None => Js.Promise.reject(Debug.toExn(exn))
             };
           } else {
             Js.Promise.reject(Debug.toExn(exn));
           }
         | None => Js.Promise.reject(Debug.toExn(exn))
         };
       })
  );


let handleUniqueError = (~name: string, ~message: string) =>
  catchUniqueError(~name, ~handle=_exn =>
    Js.Promise.reject(KnexUtils.makeError(message))
  );

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.