Skip to content

Instantly share code, notes, and snippets.

@koistya
Last active September 2, 2016 04:01
Show Gist options
  • Save koistya/78a950371d2a10b550be to your computer and use it in GitHub Desktop.
Save koistya/78a950371d2a10b550be to your computer and use it in GitHub Desktop.
Express-based API Endpoint Sample

src/server.js

import Express from 'express'
import bodyParser from 'body-parser';
import sql from 'mssql';
import config from './config';

const server = new Express();

server.use(bodyParser.urlencoded({ extended: true }));
server.use(bodyParser.json());
server.use(require('./api/sites.js'));

sql.connect(config.database, err => {
  if (err) {
    console.error('Failed to open a SQL Server connection.', err.stack);
  }
  server.listen(process.env.PORT);
});

src/api/sites.js

import sql from 'mssql';
import validator from 'validator';
import { Router } from 'express';

const router = new Router();

router.post('/sites', async (req, res, next) => {
  try {
    const model = req.body;
    // TODO: Validate the model
    const request = new sql.Request(connection);
    const dataset = await request.query(`
      INSERT INTO Site (...) VALUES (...);
      SELECT ... FROM Site WHERE SiteID = @@IDENTITY;
    `);
    res.status(201).send(dataset[0]);
  } catch (err) {
    next(err);
  }
});

export default router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment