Giter VIP home page Giter VIP logo

functions's Introduction

functions

Build Node

JavaScript and TypeScript utilities for Netlify Functions.

Installation

npm install @netlify/functions

Usage

On-demand Builders

To use On-demand Builders, wrap your function handler with the builder function.

  • With JavaScript:

    const { builder } = require('@netlify/functions')
    
    const handler = async (event, context) => {
      return {
        statusCode: 200,
        body: JSON.stringify({ message: 'Hello World' }),
      }
    }
    
    exports.handler = builder(handler)
  • With TypeScript:

    import { builder, Handler } from '@netlify/functions'
    
    const myHandler: Handler = async (event, context) => {
      return {
        statusCode: 200,
        body: JSON.stringify({ message: 'Hello World' }),
      }
    }
    
    const handler = builder(myHandler)
    
    export { handler }

Scheduled Functions (currently in beta)

To use Scheduled Functions, wrap your function handler with the schedule function.

  • With JavaScript:

    const { schedule } = require('@netlify/functions')
    
    exports.handler = schedule('5 4 * * *', async () => {
      console.log("It's 04:05 AM!")
    })
  • With TypeScript:

    import { schedule } from '@netlify/functions'
    
    export const handler = schedule("5 4 * * *", async () => {
      console.log("It's 04:05 AM!")
    })

TypeScript typings

This module exports typings for authoring Netlify Functions in TypeScript.

import { Handler } from '@netlify/functions'

const handler: Handler = async (event, context) => {
  return {
    statusCode: 200,
    body: JSON.stringify({ message: 'Hello World' }),
  }
}

export { handler }

The following types are exported:

  • Handler
  • HandlerCallback
  • HandlerContext
  • HandlerEvent
  • HandlerResponse

Contributors

Please see CONTRIBUTING.md for instructions on how to set up and work on this repository. Thanks for contributing!

functions's People

Contributors

anmonteiro avatar ascorbic avatar danez avatar dependabot[bot] avatar dustincrogers avatar dwwoelfel avatar eduardoboucas avatar ehmicky avatar emilyzhang avatar ercgrat avatar erezrokah avatar github-actions[bot] avatar ingride avatar jgantunes avatar karagulamos avatar khendrikse avatar lexicondevil avatar lukasholzer avatar mraerino avatar netlify-team-account-1 avatar notwoods avatar pcn avatar pimm avatar renovate[bot] avatar sgrove avatar skn0tt avatar token-generator-app[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

functions's Issues

Cant Start Netlify Dev

I get this error. But I want to uninstall emails plugin which is causing the error.

How can I fix this? Im on latest netlify functions 1.4.0

$ netlify dev   
\◈ Netlify Dev ◈
◈ Injecting environment variable values for all scopes
◈ Injected site settings env var: MAILGUN_DOMAIN
◈ Injected site settings env var: MAILGUN_PROVIDER_API_KEY
◈ Injected site settings env var: MAILJET_KEY
◈ Injected site settings env var: MAILJET_SECRET
◈ Setting up local development server
​
❯ Installing plugins
   - @netlify/[email protected]
   - @netlify/[email protected]
​
  Dependencies installation error                               
────────────────────────────────────────────────────────────────
​
  Error message
  Error while installing dependencies in /Users/theobouwman/dev/projects/momo/momo-website/.netlify/plugins/
​​
  Resolved config
  build:
    command: npm run build
    commandOrigin: config
    publish: /Users/theobouwman/dev/projects/momo/momo-website/.next
    publishOrigin: config
  functionsDirectory: /Users/theobouwman/dev/projects/momo/momo-website/netlify/functions
  plugins:
    - inputs: {}
      origin: ui
      package: '@netlify/plugin-nextjs'
    - inputs: {}
      origin: ui
      package: '@netlify/plugin-emails'
 ›   Error: Could not start local development server

Error while installing dependencies in /Users/theobouwman/dev/projects/momo/momo-website/.netlify/plugins/


Error: Error while installing dependencies in /Users/theobouwman/dev/projects/momo/momo-website/.netlify/plugins/

    at runCommand (file:///Users/theobouwman/.config/yarn/global/node_modules/@netlify/build/lib/install/main.js:20:24)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async installMissingPlugins (file:///Users/theobouwman/.config/yarn/global/node_modules/@netlify/build/lib/install/missing.js:16:5)
    at async handleMissingPlugins (file:///Users/theobouwman/.config/yarn/global/node_modules/@netlify/build/lib/plugins/resolve.js:97:5)
    at async resolvePluginsPath (file:///Users/theobouwman/.config/yarn/global/node_modules/@netlify/build/lib/plugins/resolve.js:32:29)
    at async tGetPluginsOptions (file:///Users/theobouwman/.config/yarn/global/node_modules/@netlify/build/lib/plugins/options.js:12:29)
    at async tGetPluginsOptions (file:///Users/theobouwman/.config/yarn/global/node_modules/@netlify/build/lib/time/main.js:18:63)
    at async initAndRunBuild (file:///Users/theobouwman/.config/yarn/global/node_modules/@netlify/build/lib/core/build.js:241:66)
    at async runAndReportBuild (file:///Users/theobouwman/.config/yarn/global/node_modules/@netlify/build/lib/core/build.js:144:156)
    at async tExecBuild (file:///Users/theobouwman/.config/yarn/global/node_modules/@netlify/build/lib/core/build.js:92:127)


Consider moving to a 1.x.x release?

Describe the bug

Versions under a 0.x.x release imply a break in compatibility but no BC changes are listed in the changelog. (See semver docs).

There are no BC breaks listed in the changelog — unclear if there aren't any or if they're just undocumented. When upgrading any 0.x.x version or major release, you want to understand how risky this process is in advance.

I would suggest to consider changing to a v1.x.x release which has better understood major/minor/bugfix semantics, especially given people are using this package (102,368 weekly downloads).

Thanks!

Configuration

N/a

Pull requests

This is more of a semantic/docs change but let me know if I can assist.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/fossa.yml
  • actions/checkout v3
.github/workflows/pre-release.yml
  • actions/checkout v3
  • actions/setup-node v3
.github/workflows/release-please.yml
  • navikt/github-app-token-generator a8ae52448279d468cfbca5cd899f2457f0b1f643
  • GoogleCloudPlatform/release-please-action v3
  • actions/checkout v3
  • actions/setup-node v3
.github/workflows/workflow.yml
  • actions/checkout v3
  • actions/setup-node v3
  • actions/setup-node v3
  • codecov/codecov-action v3
npm
package.json
  • @netlify/serverless-functions-api 1.16.2
  • @arethetypeswrong/cli ^0.15.0
  • @commitlint/cli ^17.0.0
  • @commitlint/config-conventional ^17.0.0
  • @netlify/eslint-config-node ^7.0.1
  • ava ^2.4.0
  • husky ^7.0.4
  • npm-run-all2 ^5.0.0
  • nyc ^15.0.0
  • publint ^0.2.7
  • semver ^7.5.4
  • tsd ^0.31.0
  • tsup ^8.0.2
  • typescript ^4.4.4
  • node >=14.0.0

  • Check this box to trigger a request for Renovate to run again on this repository

Publish edge functions runtime types

The types for Context are currently only available in Deno. We should also publish them somewhere they can be consumed by Node.js code, and this package is probably the most sensible place. Feel free to move if needed!

Netlify DEPLOY_URL and DEPLOY_PRIME_URL are undefined in deploy preview for function

Describe the bug

Netlify DEPLOY_URL and DEPLOY_PRIME_URL are undefined in deploy preview.

Not sure if this is the correct repository. If its not please let me know which one is?

Steps to reproduce

  1. Fork this simple Next.js app (npx create-next-app) https://github.com/watadarkstar/repro-nextjs-netlify-deploy-url
  2. Deploy to Netlify
  3. Visit the preview URL /api/hello i.e. https://61ef4b8c60b7120008731b5e--dazzling-ride-812dba.netlify.app/api/hello

Watch the ___netlify-handler function logs and you will see it prints undefined for both variables yet Netlify is supposed to auto-configure these env variables for you: https://docs.netlify.com/configure-builds/environment-variables/#deploy-urls-and-metadata

In addition to the variables you choose to declare, Netlify has a number of pre-defined variables built in. The following variables are automatically set for your builds, and their values are not changeable.

DEPLOY_URL: URL representing the unique URL for an individual deploy. It starts with a unique ID that identifies the deploy; for example, https://5b243e66dd6a547b4fee73ae--petsof.netlify.app.

DEPLOY_PRIME_URL: URL representing the primary URL for an individual deploy, or a group of them, like branch deploys and Deploy Previews; for example, https://feature-branch--petsof.netlify.app or https://deploy-preview-1--petsof.netlify.app.

Code

https://github.com/watadarkstar/repro-nextjs-netlify-deploy-url/blob/main/pages/api/hello.js

Configuration

Please enter the following command in a terminal and copy/paste its output:

 System:
    OS: macOS 11.4
    CPU: (8) x64 Apple M1
    Memory: 142.12 MB / 16.00 GB
    Shell: 3.2.2 - /usr/local/bin/fish
  Binaries:
    Node: 16.11.0 - ~/.nvm/versions/node/v16.11.0/bin/node
    Yarn: 1.22.17 - ~/.nvm/versions/node/v16.11.0/bin/yarn
    npm: 8.0.0 - ~/.nvm/versions/node/v16.11.0/bin/npm
    Watchman: 2022.01.03.00 - /opt/homebrew/bin/watchman```

Invalid types due to not found package reference

Rennovate bot is attempting to upgrade us to @netlify/functions v2 (sveltejs/kit#10600), and this newest release looks like it might be broken as it causes our type checking to fail

Describe the bug

../../node_modules/.pnpm/@[email protected]/node_modules/@netlify/serverless-functions-api/dist/cookie_store.d.ts:1:24 - error TS2307: Cannot find module '@netlify/node-cookies' or its corresponding type declarations.

1 import { Cookie } from '@netlify/node-cookies';
                         ~~~~~~~~~~~~~~~~~~~~~~~


Found 1 error in ../../node_modules/.pnpm/@[email protected]/node_modules/@netlify/serverless-functions-api/dist/cookie_store.d.ts:1

Configuration

pnpm: 8.6.12 - ~/.local/share/pnpm/pnpm

Cannot find module '@netlify/functions'

Hello. So I'm using scheduled functions and along with the dev env/mode it's working fine, I can serve it and invoke it. But as long I'm putting this to the server I have this error:

ERROR	Uncaught Exception 	{"errorType":"Runtime.ImportModuleError","errorMessage":"Error: Cannot find module '@netlify/functions' ... 

The package is defined as a dependency in the package.json, and this is my function:

const { schedule } = require('@netlify/functions')

exports.handler = schedule('@hourly', async (event) => {
  const eventBody = JSON.parse(event.body)
  console.log(`Next function run at ${eventBody.next_run}.`)
  // function init
  return {
    statusCode: 200,
  }
})

Netlify config:

[build]
    functions = "functions"
     publish = "./"

[functions]
    directory = "functions/"
    external_node_modules = ["canvas", "jsdom"]

Functions are enabled on the Labs and Project page. What is wrong? Thanks for the help in advance.

Invalid type definitions - static import of ESM types from CJS types

Describe the bug

../../node_modules/.pnpm/@[email protected]/node_modules/@netlify/functions/dist/function/v2.d.ts:1:30 - error TS1479: The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. Consider writing a dynamic 'import("@netlify/serverless-functions-api")' call instead.

1 export type { Context } from '@netlify/serverless-functions-api';
                               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Found 1 error in ../../node_modules/.pnpm/@[email protected]/node_modules/@netlify/functions/dist/function/v2.d.ts:1

Configuration

Import the library in a project which has the following in the tsconfig.json:

		"module": "node16",
		"moduleResolution": "node16",

This issue can be worked around with "skipLibCheck": true, so ensure that is not set when reproducing. It is not set by default.

Scheduled Functions feature requests

Congrats on launching Scheduled Functions! i've been working on a similar product and thought I should note down immediate observations on features you may wish to add.

Feature menu for you to choose:

  • Manual trigger in UI and in CLI - no need to write code to manual trigger
    • UI to backfill failed runs?
  • Manual pause in UI and CLI
  • View more than 1 next event in UI and in CLI
    • useful as sanity check in case user typed their cron syntax
    • basically anything doable via code should be available in UI and CLI and vice versa
  • jitter start aka (+/- 100ms) - useful for bots, spreading out spikes
  • set/update max # of invocations until schedule terminates itseld
  • allow user to specify timezone, dont assume UTC
  • "Last of" quartz scheduling syntax aka Last weekday of month, last Friday of month, see cloudflare
  • holiday exclusion calendar
  • ability to return value in function that will can be used in next invocation
    • beware overlapping schedules/background
  • context value or method to check amount of time until next invocation
  • function that can update its own schedule

you should know how to reach me if you need clarification on any of these. and of course, no offense taken if all are rejected

`identity` type doesn't match docs

Describe the bug

This repo's typings suggests that you access the Netlify Identity instance through context.identity, but the Netlify docs suggests its context.clientContext.identity.

Configuration

N/A

Pull requests

Let me know if this is correct or not. I can make a pull request to either move or copy the type.

`Handler` types incorrect for background functions

Describe the bug

Handler types incorrect for background functions.

In the docs, there are many examples where a Handler function returns without a value. Additionally, the return value of a background function is irrelevant since they always return a 200 response.
But the type for Handler forces the function to return a Response which is confusing and somewhat misleading.

Configuration
@netlify/functions 1.2.0

Code inside function can break the Netlify site

Describe the bug

I was in the middle of implementing Netlify Identity using Functions and after pushing the code below, I was a bit concerned to see it broke the https://app.netlify.com/sites/<site>/identity page:

image

Function:

import fetch from 'node-fetch';

export async function handler(e, context) {
  const { identity, user } = context.clientContext

  if (user) {
    return fetch(identity.url + '/admin/users/' + user.sub, {
      method: 'PUT',
      headers: {
        Authorization: 'Bearer ' + identity.token,
      },
      body: JSON.stringify({
        app_metadata: { roles: 'member' },
      }),
    }).then((response) => response.json()).then((data) => {
      return { statusCode: 204 };
    });
  } else {
    return {
      statusCode: 401,
      body: JSON.stringify({ message: 'Unauthorized' }),
    };
  }
}

The root cause is this line:

        app_metadata: { roles: 'member' },

After changing roles to an array, then the Identity page was fine again.

        app_metadata: { roles: ['member'] },

IMHO no code inside a function should be able to break the page like this.

Configuration

System:
OS: Windows 10 10.0.19044
CPU: (8) x64 Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
Memory: 12.18 GB / 31.95 GB
Binaries:
Node: 16.20.0 - C:\Program Files\nodejs\node.EXE
npm: 8.19.4 - C:\Program Files\nodejs\npm.CMD

Update legacy explorers.netlify.com link urls found on functions.netlify.com

Which problem is this feature request solving?

We have decided to retire the explorers.netlify.com site and replace it with suitable redirects to their relevant YouTube urls. Updating legacy explorers.netlify.com link urls found on functions.netlify.com will help with SEO and page load speed. Instead of redirecting users to their legacy link's new relevant YouTube url, we want to land the user directly onto the new relevant YouTube url to pass all SEO value straight to the YouTube video and not encounter a redirect which impacts page load time.

Describe the solution you'd like

Update legacy explorers.netlify.com link urls found on functions.netlify.com to their relevant YouTube urls in the backlinks tab in the explorers.netlify.com migration spreadsheet

Describe alternatives you've considered

Can you submit a pull request?

No

[security] Enforce Branch Protections

This is an issue generated by (for-internal-use-only)github-tools

Description

This repository has exceeded the development grace period, and the repo owner must decide if branch protections should be enforced.
If this repository houses code used in production in any capacity, branch protections must be enforced. Read (for-internal-use-only)here for more details

What do I need to do?

  • You can control whether or not branch protections are enforced by exclusively creating either of the labels:
    'enforce-branch-protections: true' or 'enforce-branch-protections: false'
  • If there is no branch protection control label, this issue will be recreated.
  • Once you have created either label, you can close this issue.
  • If you have issues or questions, please reach out to #internal-security-n-compliance on slack.

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined

Remove query parameters

A/ @mheffner
C/ @mrdg

For initial MVP we want to remove the query parameters from the function template since we won't be using them for caching in the initial release.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.