Git Product home page Git Product logo

fastify-oracle's Introduction

fastify-oracle

Greenkeeper badge

JavaScript Style Guide Build Status Coverage Status

This module provides access to an Oracle database connection pool via the oracledb module. It decorates the Fastify instance with an oracle property that is a connection pool instance.

When the Fastify server is shutdown, this plugin invokes the .close() method on the connection pool.

Install

npm i fastify-oracle --save

Usage

Add it to you project with register and you are done! This plugin will add the oracle namespace in your Fastify instance, with the following properties:

getConnection: the function to get a connection from the pool
pool: the pool instance
query: a utility to perform a query _without_ a transaction
transact: a utility to perform multiple queries _with_ a transaction

Examples

The plugin provides the basic functionality for creating a connection and executing statements such as

const fastify = require('fastify')()

fastify.register(require('fastify-oracle'), {
  pool: {
    user: 'foo',
    password: 'bar',
    connectString: 'oracle.example.com:1521/foobar'
  }
})

fastify.get('/db_data', async function (req, reply) {
  let connection
  try {
    connection = await this.oracle.getConnection()
    const { rows } = await connection.execute('SELECT 1 AS FOO FROM DUAL')
    return rows
  } finally {
    if (connection) await connection.close()
  }
})

fastify.listen(3000, (err) => {
  if (err) {
    fastify.log.error(err)
    // Manually close since Fastify did not boot correctly.
    fastify.close(err => {
      process.exit(1)
    })
  }

  // Initiate Fastify's shutdown procedure so that the plugin will
  // automatically close the connection pool.
  process.on('SIGTERM', fastify.close.bind(fastify))
})

The query feature can be used for convenience to perform a query without a transaction

const fastify = require('fastify')

fastify.register(require('fastify-oracle'), {
  pool: {
    user: 'travis',
    password: 'travis',
    connectString: 'localhost/xe'
  } 
})

fastify.post('/user/:username', (req, reply) => {
  // will return a promise, fastify will send the result automatically
  return fastify.oracle.query('SELECT * FROM USERS WHERE NAME = :name', { name: 'james' })
})

/* or with a callback

fastify.oracle.query('SELECT * FROM USERS', function onResult (err, result) {
  reply.send(err || result)
})

*/

See node-oracledb documentation for all available usage options.

The transact feature can be used for convenience to perform multiple queries with a transaction

const fastify = require('fastify')

fastify.register(require('fastify-oracle'), {
  pool: {
    user: 'travis',
    password: 'travis',
    connectString: 'localhost/xe'
  } 
})

fastify.post('/user/:username', (req, reply) => {
  // will return a promise, fastify will send the result automatically
  return fastify.oracle.transact(async conn => {
    // will resolve to commit, or rollback with an error
    return conn.execute(`INSERT INTO USERS (NAME) VALUES('JIMMY')`)
  })
})

/* or with a callback

fastify.oracle.transact(conn => {
    return conn.execute('SELECT * FROM DUAL')
  },
  function onResult (err, result) {
    reply.send(err || result)
  }
})

*/

/* or with a commit callback

fastify.oracle.transact((conn, commit) => {
  conn.execute('SELECT * FROM DUAL', (err, res) => {
    commit(err, res)
  });
})

*/

Options

fastify-oracle requires an options object with at least one of the following properties:

  • pool: an oracledb pool configuration object
  • poolAlias: the name of a pool alias that has already been configured. This takes precedence over the pool option.
  • client: an instance of an oracledb connection pool. This takes precedence over the pool and poolAlias options.

Other options are as follows

  • name: (optional) can be used in order to connect to multiple oracledb instances. The first registered instance can be accessed via fastify.oracle or fastify.oracle.<dbname>. Note that once you register a named instance, you will not be able to register an unnamed instance.
  • outFormat: (optional) sets the outFormat of oracledb. Should be 'ARRAY' or 'OBJECT'. Default: 'ARRAY'
  • fetchAsString: (optional) the column data of specified types are returned as a string instead of the default representation. Should be an array of valid data types. Valid values are ['DATE', 'NUMBER', 'BUFFER', 'CLOB']. Default [].
const fastify = require('fastify')()

fastify
  .register(require('fastify-oracle'), {
    pool: {
      user: 'foo',
      password: 'bar',
      connectString: 'oracle.example.com:1521/ora1'
    },
    name: 'ora1'
  })
  .register(require('fastify-oracle'), {
    pool: {
      user: 'foo',
      password: 'bar',
      connectString: 'oracle.example.com:1521/ora2'
    },
    name: 'ora2'
  })

fastify.get('/db_1_data', async function (req, reply) {
  let conn
  try {
    conn = await this.oracle.ora1.getConnection()
    const result = await conn.execute('select 1 as foo from dual')  
    return result.rows
  } finally {
    if (conn) {
      conn.close().catch((err) => {})
    }
  } 
})

fastify.get('/db_2_data', async function (req, reply) {
  let conn
  try {
    conn = await this.oracle.ora2.getConnection()
    const result = await conn.execute('select 1 as foo from dual')  
    return result.rows
  } finally {
    if (conn) {
      conn.close().catch((err) => {})
    }
  }
})

The oracledb instance is also available via fastify.oracle.db for accessing constants and other functionality:

fastify.get('/db_data', async function (req, reply) {
  let conn
  try {
    conn = await this.oracle.ora1.getConnection()
    const result = await conn.execute('select 1 as foo from dual', { }, { outFormat: this.oracle.db.OBJECT })
    return result.rows
  } finally {
    if (conn) {
      conn.close().catch((err) => {})
    }
  } 
})

If needed pool instance can be accessed via fastify.oracle[.dbname].pool

License

MIT License

Acknowledgements

Thanks to

  • James Sumners, who is the original author of this plugin, for his work and transferring his repository to me.
  • Vincit for his Travis Oracle work.

fastify-oracle's People

Contributors

cemremengu avatar greenkeeper[bot] avatar jsumners avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar

fastify-oracle's Issues

An in-range update of fastify is breaking the build 🚨

The devDependency fastify was updated from 2.3.0 to 2.4.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

fastify is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v2.4.0

Features

  • Use secure-json-parse instead of bourne (#1619)
  • Add option to disable request start and end logging (#1629)

Fixes

  • Add typings for disableRequestLogging option (#1633)
  • Catches onRoute hooks errors (#1651)
  • Emit warning synchronously (#1657)
  • Hooks: throw on incorrect async function (#1608)
  • fix(types): fix register options (#1644)

Documentation

  • add: more example on how use the $ref keyword (#1613)
  • Minor host binding documentation rewrite: (#1616)
  • Add fastify-feature-flags plugin to Ecosystem (#1614)
  • docs: fix a broken anchor tag in Logging page (#1622)
  • improve docs of fastify.close() (#1632)
  • Added fastify-decorators to Ecosystem.md (#1645)
  • offboarding steps (#1646)
  • Add fastify-objectionjs plugin to the Ecosystem (#1638)
  • add example repo link (#1648)
  • Make some spelling and grammar corrections to TS.md (#1640)
  • docs(reply): clarify settings headers (#1642)
  • Docs: add links for Ajv i18n and custom errors (#1588)
  • Updated docs to reflect internal reorg (#1575)

Internals

  • chore(travis) add 12 (#1611)
  • add node v12 to ci (#1610)
  • Updated azure pipelines configuration (#1639)
  • chore(package): update dns-prefetch-control to version 0.2.0 (#1641)
  • add tap into greenkeeper ignore list (#1643)
  • Fix typo in azure-pipelines.yml (#1649)
  • chore(package): update flatstr to version 1.0.12 (#1653)
  • chore(package): update send to version 0.17.0 (#1627)
  • internal: moved route code (#1625)
Commits

The new version differs by 30 commits.

  • a6fa039 Bumped v2.4.0
  • ff5bfdd docs(reply): clarify settings headers (#1642)
  • 9e65ca4 internal: moved route code (#1625)
  • d377ebe Make some spelling and grammar corrections to TS.md (#1640)
  • 1f3c0de Emit warning synchronously (#1657)
  • dd05901 chore(package): update send to version 0.17.0 (#1627)
  • d1dab14 add example repo link (#1648)
  • 481d809 Catches onRoute hooks errors (#1651)
  • 6e4e662 chore(package): update flatstr to version 1.0.12 (#1653)
  • f627bbf fix(types): fix register options (#1644)
  • a210899 offboarding steps (#1646)
  • 0ce4f0d Fix typo in azure-pipelines.yml (#1649)
  • 5a01a55 Added fastify-decorators to Ecosystem.md (#1645)
  • d6b5354 add tap into greenkeeper ignore list (#1643)
  • edff93c Docs: add links for Ajv i18n and custom errors (#1588)

There are 30 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of fastify-plugin is breaking the build 🚨

The dependency fastify-plugin was updated from 1.5.0 to 1.6.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

fastify-plugin is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v1.6.0

📚 PR:

  • chore(package): update fastify to version 2.0.0
  • Updated to fastify v2
  • fix(package): update semver to version 6.0.0
  • Adds defaults generic types to main function
  • Adds test for fastify plugin’s generic typings
  • Organize typescript testing (#63)
  • update all dependencies to latest, the same of Fastify (latest) (#64)
  • ignore tap (#71)
Commits

The new version differs by 10 commits.

  • 2dce5cd Bumped v1.6.0.
  • 20caf8a Added Node 12 to .travis.yml
  • 345c750 Adds test for fastify plugin’s generic typings
  • 89721bb Adds defaults generic types to main function
  • 966248c ignore tap (#71)
  • e1601e4 fix(package): update semver to version 6.0.0
  • ab15760 Updated to fastify v2
  • 9d3a7ff chore(package): update fastify to version 2.0.0
  • 24eb09d update all dependencies to latest, the same of Fastify (latest) (#64)
  • 5bc3d7d Organize typescript testing (#63)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Travis is broken

Travis will not work until someone figures out how to get the oracledb driver to install within the Travis containers. Frankly, I'm not bothered enough.

Question: Multiple oracle pool instances?

Is it possible at the moment to register two oracle plugins with different names for accessing multiple oracledb instances such as in the mongodb plugin?

fastify
  .register(require('fastify-mongodb'), { url: 'mongodb://mongo1/mydb', name: 'MONGO1' })
  .register(require('fastify-mongodb'), { url: 'mongodb://mongo2/otherdb', name: 'MONGO2' })

Couldn't see anything that supports this in the code but just wanted to ask. I am going to attempt to add this feature if it is not present. What do you think?

Error when installing via npm

Hi, I'm trying to install fastify-oracle on Windows10 using npm, but I keep getting errors.

oracledb ERR! NJS-067: a pre-built node-oracledb binary was not found for Node.js v12.18.3 (NODE_MODULE_VERSION=72) on win32 x64
oracledb ERR! Try compiling node-oracledb source code using https://oracle.github.io/node-oracledb/INSTALL.html#github
npm WARN [email protected] No description
npm WARN [email protected] No repository field.

npm ERR! code ELIFECYCLE
npm ERR! errno 87
npm ERR! [email protected] install: `node package/install.js`
npm ERR! Exit status 87
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

I believe that the package is not up to date (oracledb3.1.2 seems to be depreciated)
It can also be my fault and I didn't see something when trying :)

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.