如何在AWS Lambda上修复猫鼬打字稿错误?

时间:2019-04-16 02:36:04

标签: typescript mongoose serverless-framework

我正在尝试使用无服务器框架AWS lambda和mongoose建立对Mongo Atlas数据库的简单调用。

我目前正在使用来自无服务器的最新命令来设置打字稿:create -t aws-nodejs-typescript

serverless.yaml

plugins:
  - serverless-webpack

provider:
  name: aws
  runtime: nodejs8.10
  region: us-east-1

tsconfig.json

  "compilerOptions": {
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es2017",
    "module": "commonjs",
    "outDir": "lib",
    "removeComments": true,
    "pretty": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true
  },
  "exclude": [
    "node_modules"
  ]
}

我有一个导入的文件来处理实际的连接。

connect.ts

export const mongoose = require('mongoose')
export const Schema = mongoose.Schema

mongoose.Promise = global.Promise
let isConnected: boolean = false

export const connectToDatabase = () => {
  if (isConnected) {
    console.log('using existing database connection')
    return Promise.resolve()
  } else {
    console.log('using new database connection', { isConnected })
    return mongoose
      .connect(
        encodeURI(`${process.env.DB}`)
      )
      .then((db: any) => {
        console.log(db)
        isConnected = true
      })
  }
}

然后导入到我的处理程序函数中。

handler.ts


import {
  connectToDatabase,
  defaultResponseHeader,
} from '../utils/mongo-helpers'
import { user } from '../utils/users'

module.exports.hello = async (event, context) => {
  console.log('started')
  context.callbackWaitsForEmptyEventLoop = false

  console.log(user)
  connectToDatabase().then(() => {
    console.log('in connect')
    const doc = user.findOne()
    console.log(doc)
    console.log(event)

    return doc
  })
}

当我将此部署到AWS lambda并尝试进行测试时,出现以下错误:

  "errorMessage": "Unexpected token *",
  "errorType": "SyntaxError",
  "stackTrace": [
    "SyntaxError: Unexpected token *",
    "createScript (vm.js:80:10)",
    "Object.runInThisContext (vm.js:139:10)",
    "Module._compile (module.js:616:28)",
    "Object.Module._extensions..js (module.js:663:10)",
    "Module.load (module.js:565:32)",
    "tryModuleLoad (module.js:505:12)",
    "Function.Module._load (module.js:497:3)",
    "Module.require (module.js:596:17)",
    "require (internal/module.js:11:18)"
  ]
}

以及以下日志

SyntaxError: Unexpected token *
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:616:28)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)

这似乎是编译错误或未正确导入的错误。

我尝试了不同版本的导入或要求猫鼬,但似乎无济于事。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

至少导出require('mongoose')似乎是不需要的。

对我有用的只是遵循官方准则: https://mongoosejs.com/docs/lambda.html

并使用serverless-plugin-typescript: https://github.com/prisma/serverless-plugin-typescript