Skip to content
This repository was archived by the owner on Sep 12, 2019. It is now read-only.

add working basic templates for netlify functions:create #22

Merged
merged 3 commits into from
Mar 15, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 20 additions & 46 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"ascii-table": "0.0.9",
"get-port": "^4.1.0",
"http-proxy": "^1.17.0",
"inquirer": "^6.2.2",
"netlify": "ssh+git://[email protected]:netlify/js-client-private",
"netlify-rules-proxy": "git+ssh://[email protected]/netlify/netlify-rules-proxy.git",
"static-dev-server": "^1.0.0",
Expand Down
63 changes: 43 additions & 20 deletions src/commands/functions/create.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,27 @@ const fs = require('fs')
const path = require('path')
const { flags } = require('@oclif/command')
const Command = require('@netlify/cli-utils')

const template = `async function hello() {
return Promise.resolve('Hello, World')
}

exports.handler = async function(event, context) {
try {
const body = await hello()
return { statusCode: 200, body }
} catch (err) {
return { statusCode: 500, body: err.toString() }
}
}
`
const inquirer = require('inquirer')

class FunctionsCreateCommand extends Command {
async run() {
const { flags, args } = this.parse(FunctionsCreateCommand)
const { name } = args
const name = await getNameFromArgs(args)
const { config } = this.netlify

const templates = fs
.readdirSync(path.resolve(__dirname, '../../functions-templates'))
.filter(x => path.extname(x) === '.js') // only js templates for now
const { templatePath } = await inquirer.prompt([
{
name: 'templatePath',
message: 'pick a template',
type: 'list',
choices: templates.map(t => ({ name: path.basename(t, '.js') }))
}
])
const template =
'// scaffolded from Netlify Dev \n\n' +
fs.readFileSync(path.resolve(__dirname, `../../functions-templates/${templatePath}.js`)).toString()
this.log(`Creating function ${name}`)

const functionsDir = flags.functions || (config.build && config.build.functions)
Expand Down Expand Up @@ -56,18 +56,23 @@ class FunctionsCreateCommand extends Command {
// Ignore
}
} else if (fs.existsSync(functionPath.replace(/\.js/, ''))) {
this.log(`A folder version of the function ${name} alreadt exists at ${functionPath.replace(/\.js/, '')}`)
this.log(`A folder version of the function ${name} already exists at ${functionPath.replace(/\.js/, '')}`)
process.exit(1)
}

fs.writeFileSync(functionPath, template)
}
}

FunctionsCreateCommand.args = [{ name: 'name' }]
FunctionsCreateCommand.args = [
{
name: 'name',
// required: true, // tried this but the error message is very ugly
description: 'name of your new function file inside your functions folder'
}
]

FunctionsCreateCommand.description = `create a new function locally
`
FunctionsCreateCommand.description = `create a new function locally`

FunctionsCreateCommand.examples = ['netlify functions:create hello-world']

Expand All @@ -79,3 +84,21 @@ FunctionsCreateCommand.flags = {
})
}
module.exports = FunctionsCreateCommand

// prompt for a name if name not supplied
// we tried using required:true in oclif args (see below) but the error msg was very ugly
async function getNameFromArgs(args) {
let { name } = args
if (!name) {
let responses = await inquirer.prompt([
{
name: 'name',
message: 'name your function: ',
type: 'input',
validate: val => !!val && /^[a-z0-9]+$/i.test(val) // make sure it is not undefined and is alphanumeric
}
])
name = responses.name
}
return name
}
11 changes: 11 additions & 0 deletions src/functions-templates/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
## note to devs

place new templates here and our CLI will pick it up. currently only works for single file `.js` templates.

## why place it in this separate folder

we dont colocate this inside `src/commands/functions` because oclif will think it's a new command.

## future dev thoughts

we will want a way to scale this to TS and Go as well.
12 changes: 12 additions & 0 deletions src/functions-templates/hello-world.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
async function hello() {
return Promise.resolve('Hello, World')
}

exports.handler = async function(event, context) {
try {
const body = await hello()
return { statusCode: 200, body }
} catch (err) {
return { statusCode: 500, body: err.toString() }
}
}
22 changes: 22 additions & 0 deletions src/functions-templates/node-fetch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import fetch from 'node-fetch'
export async function handler(event, context) {
try {
const response = await fetch('https://api.chucknorris.io/jokes/random')
if (!response.ok) {
// NOT res.status >= 200 && res.status < 300
return { statusCode: response.status, body: response.statusText }
}
const data = await response.json()

return {
statusCode: 200,
body: JSON.stringify({ msg: data.value })
}
} catch (err) {
console.log(err) // output to netlify function log
return {
statusCode: 500,
body: JSON.stringify({ msg: err.message }) // Could be a custom message or object i.e. JSON.stringify(err)
}
}
}