npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ndm-schema-generator

v1.0.11

Published

Tool to generate a database schema object for use with the node-data-mapper project.

Downloads

3

Readme

ndm-schema-generator

A tool to generate a database schema object for use with the node-data-mapper project.

When using node-data-mapper a database schema object is required to describe how each table and column will be mapped from a tablular format to a normalized format (from rows and columns to JavaScript objects and arrays). Manually creating and maintaining a database schema object is cumbersome and error prone, so it's recommended that the database schema object be generated automatically at application start-up time. After all, the database itself has metadata available that describes the tables, columns, data types, maximum lengths, nullability, etc. Using a generator makes additions and modifications to the database automatic. So if, for example, a column is added to the database, a simple application restart gives the ORM knowledge of the new column. This tool provides a working example that can be used to generate a database schema object, with some useful hooks for aliasing tables and columns and attaching global converters.

Table of Contents

Getting Started

First off, if you're not familiar with node-data-mapper then please read through the Getting Started section. The ndm-schema-generator is implemented in terms of node-data-mapper, and the initial setup is therefore similar.

The below example uses a fictitious bike_shops database. If you would like to run the example included in the example folder (./example/example.js), then first follow the instructions for creating the bike_shops database.

Install ndm-schema-generator
$ npm install ndm-schema-generator --save
Create a DataContext Instance

After installation, a DataContext instance needs to be set up. This object provides connection details for your database. The supplied user must have access to the INFORMATION_SCHEMA database, as it's what is queried to retrieve metadata about your database and subsequently generate the database schema object. Here's an example script that exports a DataContext instance (reference example/infoSchemaDataContext.js):

'use strict';

const ndm   = require('node-data-mapper');
const mysql = require('mysql');

let db   = new ndm.Database(require('ndm-schema-generator').information_schema);
let pool = mysql.createPool({
  host:            'localhost',
  user:            'example',
  password:        'secret',
  database:        db.getName(),
  connectionLimit: 1
});

module.exports = new ndm.MySQLDataContext(db, pool);

Generate a Database Schema Object

Example

Below is a quick example of how to generate a database schema object using the DataContext instance defined above. The example generates the schema object, performs some minor manipulation on the tables and columns, and then prints the results to the console. There are two hooks--tableCB and columnCB--that will be described in further detail below.

'use strict';

const ndm          = require('node-data-mapper');
const Generator    = require('ndm-schema-generator').Generator;
const infoSchemaDC = require('./infoSchemaDataContext');
const util         = require('util');

let generator = new Generator(infoSchemaDC);

/**
 * The table alias removes any underscores and uppercases the proceeding
 * character.  Ex: bike_shop_bikes => bikeShopBikes
 * @param table A Table object with name and alias properties.
 */
function tableCB(table) {
  table.alias = table.name.replace(/_[a-z]/g, (c) => c.substr(1).toUpperCase());
}

/**
 * Set up each column.
 * @param col A Column object with name, alias, dataType, columnType,
 *        isNullable, maxLength, and isPrimary properties.
 * @param table A Table object with name and alias properties.
 */
function columnCB(col, table) {
  // Add a converter based on the type.
  if (col.dataType === 'bit')
    col.converter = ndm.bitConverter;
}

generator
  .generateSchema('bike_shop', tableCB, columnCB)
  .then((schema) => console.log(util.inspect(schema, {depth: null})))
  .catch(console.error);

The generator.generateSchema method takes three parameters: dbName, which is a string; tableCB, a function that takes a table object as a parameter; and columnCB, which is a function that takes column and table objects as parameters.

Table Callback

The tableCB callback function is called once for each table in the database. This is the appropriate place to define global aliases for tables. In the example above, tables are defined in the database using snake_case (bike_shops and bike_shop_bikes for example). In JavaScript, however, the most common convention is camelCase. Hence, the tableCB function above take in a table object with a name in snake_case, and modifies it to have a camelCase alias.

Column Callback

The columnCB callback function is called once for each column in the database. Like the tableCB, it can be used to alias columns. In addition, it can be used to attached global converters based on data type. In the example above, a bitConverter is attached to all bit-type columns (in reality, this would most likely be attached to columns with a columnType of tinyint(1) as well). At any rate, with the above definition in place every bit-type column in the database will automatically be transformed into a boolean. One could, for example, convert all dates to UTC strings, and a system-wide format changes can then be done in a single place.