Skip to content

Instantly share code, notes, and snippets.

@kthy
Created June 9, 2022 09:35
Show Gist options
  • Save kthy/6f7794f87840fc80fda7630aaf9a8fd1 to your computer and use it in GitHub Desktop.
Save kthy/6f7794f87840fc80fda7630aaf9a8fd1 to your computer and use it in GitHub Desktop.
Sequelize demo with custom schema
const dotenv = require('dotenv');
const express = require('express');
const { Sequelize, DataTypes } = require('sequelize');
dotenv.config();
const app = express();
const port = parseInt(process.env.APP_PORT) || 3000;
const pg_connection_details = {
database: process.env.PG_DATABASE,
username: process.env.PG_USERNAME,
password: process.env.PG_PASSWORD,
host: process.env.PG_HOST || 'localhost',
port: parseInt(process.env.PG_PORT) || 5432,
dialect: 'postgres',
dialectOptions: {
ssl: {
require: true,
rejectUnauthorized: false,
}
},
};
console.debug(pg_connection_details);
const schema = process.env.PG_SCHEMA || 'custom_schema';
const sequelize = new Sequelize(pg_connection_details);
const Visit = sequelize.define('Visit', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
ip: {
type: DataTypes.INET,
allowNull: false,
},
method: {
type: DataTypes.STRING,
allowNull: false,
},
}, {
schema: schema,
timestamps: true,
createdAt: 'created_at',
updatedAt: false,
});
const db_connect = async function() {
try {
await sequelize.authenticate();
console.log('Database connection established');
await sequelize.createSchema(schema);
await sequelize.sync({ alter: true })
console.log('Sequelize models synchronized');
} catch (error) {
console.error('Unable to connect to the database:', error);
process.exit(1);
}
};
app.get('/', (req, res) => {
Visit.create({ ip: req.ip, method: req.method }).then((visit) => {
console.debug(visit.toJSON());
});
res.send('Hello World!');
});
db_connect().then(() => {
app.listen(port, () => { console.log(`App listening on port ${port}`); });
});
{
"name": "sequelize-demo-with-custom-schema",
"version": "1.0.0",
"description": "Sequelize demo with custom schema",
"main": "app.js",
"scripts": {},
"author": "Kristian Thy <kthy@utiligize.com>",
"license": "ISC",
"dependencies": {
"dotenv": "^16.0.1",
"express": "^4.18.1",
"pg": "^8.7.3",
"pg-hstore": "^2.3.4",
"sequelize": "^6.20.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment