How to use @serverless/core - 10 common examples

To help you get started, we’ve selected a few @serverless/core examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github serverless-components / tencent-website / serverless.js View on Github external
inputs.cors || null,
      inputs.protocol
    )

    // Build environment variables
    if (inputs.env && Object.keys(inputs.env).length && inputs.code.root) {
      this.context.status(`Bundling environment variables`)
      this.context.debug(`Bundling website environment variables.`)
      let script = 'window.env = {};\n'
      inputs.env = inputs.env || {}
      for (const e in inputs.env) {
        // eslint-disable-line
        script += `window.env.${e} = ${JSON.stringify(inputs.env[e])};\n` // eslint-disable-line
      }
      const envFilePath = path.join(inputs.code.root, 'env.js')
      await utils.writeFile(envFilePath, script)
      this.context.debug(`Website env written to file ${envFilePath}.`)
    }

    // If a hook is provided, build the website
    if (inputs.code.hook) {
      this.context.status('Building assets')
      this.context.debug(`Running ${inputs.code.hook} in ${inputs.code.root}.`)

      const options = { cwd: inputs.code.root }
      try {
        await exec(inputs.code.hook, options)
      } catch (err) {
        console.error(err.stderr) // eslint-disable-line
        throw new Error(
          `Failed building website via "${inputs.code.hook}" due to the following error: "${err.stderr}"`
        )
github serverless / components / templates / component-boilerplate / serverless.js View on Github external
async default(inputs = {}) {
    // use the inputs param to get component configuration from users of your component

    // Show status...
    this.context.status('Showing you around')

    await utils.sleep(2000)

    // Show a nicely formatted log statement...
    this.context.log('This is a log statement')
    this.context.log('------------')

    await utils.sleep(2000)

    // Show a nicely formatted debug statement...
    this.context.log('Printing a "debug" statement (use "--debug" to see it)...')
    this.context.log('')
    this.context.debug('This is a debug statement visible when someone uses the "serverless --debug" option')
    this.context.log('------------')

    await utils.sleep(4000)

    this.context.log('You can specify credentials in a ".env" file')
github webiny / webiny-js / components / serverless-aws-api-gateway / utils.js View on Github external
restApiId: apiId,
        type: isLambda ? "AWS_PROXY" : "HTTP_PROXY",
        integrationHttpMethod: "POST",
        uri: isLambda
            ? `arn:aws:apigateway:${region}:lambda:path/2015-03-31/functions/${endpoint.function}/invocations`
            : endpoint.proxyURI
    };

    try {
        await apig.putIntegration(integrationParams).promise();
    } catch (e) {
        if (e.code === "ConflictException") {
            // this usually happens when there are too many endpoints for
            // the same function. Retrying after couple of seconds ensures
            // any pending integration requests are resolved.
            await utils.sleep(2000);
            return createIntegration({ apig, lambda, apiId, endpoint });
        }
        throw Error(e);
    }

    // Create lambda trigger for AWS_PROXY endpoints
    if (isLambda) {
        const permissionsParams = {
            Action: "lambda:InvokeFunction",
            FunctionName: functionName,
            Principal: "apigateway.amazonaws.com",
            SourceArn: `arn:aws:execute-api:${region}:${accountId}:${apiId}/*/*`,
            StatementId: `${functionName}-${apiId}`
        };

        try {
github serverless / components / templates / component-boilerplate / serverless.js View on Github external
await utils.sleep(2000)

    // Show a nicely formatted debug statement...
    this.context.log('Printing a "debug" statement (use "--debug" to see it)...')
    this.context.log('')
    this.context.debug('This is a debug statement visible when someone uses the "serverless --debug" option')
    this.context.log('------------')

    await utils.sleep(4000)

    this.context.log('You can specify credentials in a ".env" file')
    this.context.log('Serverless Components recognizes various ENV keys from popular cloud vendors and will add them to the "this.context.credentials" object.')
    this.context.log('------------')

    await utils.sleep(6000)

    this.context.log('The "this.context" object features some useful info and methods.')
    this.context.log('Use "this.context.resourceId()" to generate a string to use for cloud resource names, to ensure no name collisions occur:')
    this.context.log('Here is the result of running "this.context.resourceId()":  "' + this.context.resourceId() + '"')
    this.context.log('------------')

    await utils.sleep(3000)

    // Save state
    // This component's state and any child component states are saved in the .serverless directory
    this.state.name = 'myComponent'
    await this.save()

    // Common provider credentials are identified in the environment or .env file and added to this.context.credentials
    // The following line assumes you have the aws-sdk package installed locally
    // const dynamodb = new AWS.DynamoDB({ credentials: this.context.credentials.aws })
github serverless-components / backend / serverless.js View on Github external
inputs.bucketName = inputs.bucketName || 'backend-' + this.context.resourceId()
    inputs.region = inputs.region || 'us-east-1'

    // Default to current working directory
    inputs.code = inputs.code || {}
    inputs.code.root = inputs.code.root ? path.resolve(inputs.code.root) : process.cwd()
    if (inputs.code.src) {
      inputs.code.src = path.join(inputs.code.root, inputs.code.src)
    }

    let exists
    if (inputs.code.src) {
      exists = await utils.fileExists(path.join(inputs.code.src, 'index.js'))
    } else {
      exists = await utils.fileExists(path.join(inputs.code.root, 'index.js'))
    }

    if (!exists) {
      throw Error(
        `No index.js file found in the directory "${inputs.code.src || inputs.code.root}"`
      )
    }

    // If a hook is provided, build the assets
    if (inputs.code.hook) {
      this.context.status('Building assets')
      this.context.debug(`Running ${inputs.code.hook} in ${inputs.code.root}.`)

      const options = { cwd: inputs.code.root }
      try {
        await exec(inputs.code.hook, options)
github serverless-components / tencent-cos / serverless.js View on Github external
if (path.sep === '\\') {
          key = key.replace(/\\/g, '/')
        }

        const itemParams = {
          Bucket: bucket,
          Region: region,
          Key: key,
          Body: fs.createReadStream(item.path)
        }
        handler = util.promisify(clients.putObject.bind(clients))
        uploadItems.push(handler(itemParams))
      })

      await Promise.all(uploadItems)
    } else if (inputs.file && (await utils.fileExists(inputs.file))) {
      // upload a single file using multipart uploads
      this.context.debug(`Uploading file ${inputs.file} to bucket ${bucket}`)

      const itemParams = {
        Bucket: bucket,
        Region: region,
        Key: inputs.key || path.basename(inputs.file),
        Body: fs.createReadStream(inputs.file)
      }
      const handler = util.promisify(clients.putObject.bind(clients))
      try {
        await handler(itemParams)
      } catch (e) {
        throw e
      }
github serverless-components / tencent-cos / serverless.js View on Github external
const appId = await this.getAppid(tencent)
      this.context.credentials.tencent.AppId = appId.AppId
    }

    const bucket = this.state.bucket || inputs.bucket
    const region = this.state.region || inputs.region || 'ap-guangzhou'

    if (!bucket) {
      throw Error('Unable to upload. Bucket name not found in state.')
    }

    this.context.debug(`Starting upload to bucket ${bucket} in region ${region}`)

    const clients = getSdk(this.context.credentials.tencent)

    if (inputs.dir && (await utils.dirExists(inputs.dir))) {
      this.context.debug(`Uploading directory ${inputs.dir} to bucket ${bucket}`)
      // upload directory contents

      const options = { keyPrefix: inputs.keyPrefix }

      const items = await new Promise((resolve, reject) => {
        try {
          resolve(klawSync(inputs.dir))
        } catch (error) {
          reject(error)
        }
      })

      let handler
      let key
      const uploadItems = []
github serverless-components / website / serverless.js View on Github external
this.context.debug(`Configuring bucket ${inputs.bucketName} for website hosting.`)
    await configureBucketForHosting(s3, inputs.bucketName)

    // Build environment variables
    inputs.env = inputs.env || {}
    if (Object.keys(inputs.env).length && inputs.code.root) {
      this.context.status(`Bundling environment variables`)
      this.context.debug(`Bundling website environment variables.`)
      let script = 'window.env = {};\n'
 
      for (const e in inputs.env) {
        // eslint-disable-line
        script += `window.env.${e} = ${JSON.stringify(inputs.env[e])};\n` // eslint-disable-line
      }
      const envFilePath = path.join(inputs.code.root, 'env.js')
      await utils.writeFile(envFilePath, script)
      this.context.debug(`Website env written to file ${envFilePath}.`)
    }

    // If a hook is provided, build the website
    if (inputs.code.hook) {
      this.context.status('Building assets')
      this.context.debug(`Running ${inputs.code.hook} in ${inputs.code.root}.`)

      const options = { 
        cwd: inputs.code.root,
        // Merge input & process env variables to be available for hooks execution
        env: Object.assign(process.env, inputs.env),
      }

      try {
        await exec(inputs.code.hook, options)
github serverless / components / templates / component-boilerplate / serverless.js View on Github external
async anything(inputs = {}) {
    this.context.status('Running Anything')
    await utils.sleep(6000)
  }
}