Skip to content

Instantly share code, notes, and snippets.

@khalidx
Last active May 19, 2021 11:52
Show Gist options
  • Save khalidx/6f2544858a2321c836acc10479f95fc0 to your computer and use it in GitHub Desktop.
Save khalidx/6f2544858a2321c836acc10479f95fc0 to your computer and use it in GitHub Desktop.
A quick api boilerplate file for express with hot-reloading and typescript support
#!/usr/bin/env node
/* The API routes and middlewares */
const server = () => import('express').then(({ default: express }) => {
const app = express()
app.get('/hello', (req, res) => {
res.json({ message: 'Hey there!' })
})
return app
})
/* The dev startup script with hot-reload */
const dev = () => import('nodemon').then(({ default: nodemon }) => {
nodemon({ script: __filename, ext: 'ts' }).on('restart', (files) => console.log('App restarted due to:', files))
})
/* The standard server start script */
const start = () => {
const port = process.env.PORT || 3000
server().then(app => app.listen(port, () => console.log(`Server listening at http://localhost:${port}`)))
}
/* A cli for starting the API server */
const cli = () => {
const args = process.argv.slice(2)
const command = args.shift()
if (command === 'dev') dev()
else start()
}
/* Can be imported as a module, or started as a CLI */
if (require.main === module) cli()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment