将功能部署到Firebase

时间:2018-07-12 23:55:50

标签: javascript json firebase push-notification webdeploy

我正在尝试将功能部署到Firebase

$ npm install firebase-tools
$ login firebase
$ firebase init functions

然后$firebase deploy --only functions$firebase deploy

package.json

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "lint": "eslint .",
    "serve": "firebase serve --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "dependencies": {
    "firebase-admin": "~5.12.1",
    "firebase-functions": "^1.0.3"
  },
  "devDependencies": {
    "eslint": "^4.12.0",
    "eslint-plugin-promise": "^3.6.0"
  },
  "private": true
}

firebase.json

{
  "functions": {
    "predeploy": [
      "npm --prefix \"%RESOURCE_DIR%\" run lint"
    ]
  }
}

$RESOURCE_DIR修改为%RESOURCE_DIR%,以避免:

  

错误:函数预部署错误:命令以非零终止   退出代码4294963238

我的功能index.js

const functions = require('firebase-functions');
var admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);
var wrotedata;
exports.Pushtrigger = functions.database.ref('/messages/{messageId}').onWrite((event) => {
    wrotedata = event.data.val();

    admin.database().ref('/pushtokens').orderByChild('uid').once('value').then((alltokens) => {
        var rawtokens = alltokens.val();
        var tokens = [];
        this.processtokens(rawtokens).then((processedtokens) => {

            for (var token in processedtokens) {
                tokens.push(token.devtoken);
            }

            var payload = {
                "notification": {
                    "title": "Notification title",
                    "body": "Notification body",
                    "sound": "default",
                    "click_action": "FCM_PLUGIN_ACTIVITY",
                    "icon": "fcm_push_icon"
                },
                "data": {
                    "message": "value1",
                    "sendername": "value2"
                }
            }
                return admin.messaging().sendToDevice(tokens, payload).then((response) => {
                    console.log('Push notifications');
                }).catch((err) => {
                    console.log(err);
                })             
        })
    })
})

function processtokens(rawtokens) {
    var promise = new Promise((resolve, reject) => {
        var processedtokens = []
        for (token in rawtokens) {
            processedtokens.push(rawtokens[token]);
        }
        resolve(processdatatokens);
    })
    return promise;
}

我尝试过:

npm install firebase-admin@latest firebase-functions@latest
npm install -g git://github.com/firebase/firebase-tools#master

但是我得到了:

  

错误:函数预部署错误:命令以非零终止   退出代码1

2018-07-12T23_38_09_788Z-调试:

0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   '--prefix',
1 verbose cli   'C:\\Users\\User\\Desktop\\pushcloud\\functions',
1 verbose cli   'run',
1 verbose cli   'lint' ]
2 info using npm@5.6.0
3 info using node@v8.9.4
4 verbose run-script [ 'prelint', 'lint', 'postlint' ]
5 info lifecycle functions@~prelint: functions@
6 info lifecycle functions@~lint: functions@
7 verbose lifecycle functions@~lint: unsafe-perm in lifecycle true
8 verbose lifecycle functions@~lint: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\Users\User\Desktop\pushcloud\functions\node_modules\.bin;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\Embarcadero\Studio\16.0\bin;C:\Users\Public\Documents\Embarcadero\Studio\16.0\Bpl;C:\Program Files (x86)\Embarcadero\Studio\16.0\bin64;C:\Users\Public\Documents\Embarcadero\Studio\16.0\Bpl\Win64;C:\Inprise\vbroker\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Python27;C:\Python27\Scripts\;C:\Users\User\AppData\Local\Programs\Python\Python35-32;C:\Users\User\AppData\Local\Programs\Python\Python35-32\Scripts;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Emgu\emgucv-windesktop 3.1.0.2282\bin\x86;C:\Program Files (x86)\Skype\Phone\;C:\php;C:\Apache2;C:\Apache2\bin;C:\Program Files\dotnet\;C:\WINDOWS\system32\config\systemprofile\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files\Java\jdk1.8.0_151\bin;C:\Users\User\AppData\Local\Android\Sdk\platform-tools;C:\Program Files\nodejs\;C:\Program Files\Git\cmd;C:\Program Files\Git\usr\bin;C:\Go\bin;C:\Program Files (x86)\Java\jre1.8.0_101\bin;C:\Users\User\AppData\Local\Programs\Python\Python35-32\Scripts\;C:\Users\User\AppData\Local\Programs\Python\Python35-32\;C:\Users\User\AppData\Local\Microsoft\WindowsApps;C:\Program Files\Microsoft VS Code\bin;C:\Users\User\AppData\Roaming\npm;C:\Users\User\go\bin
9 verbose lifecycle functions@~lint: CWD: C:\Users\User\Desktop\pushcloud\functions
10 silly lifecycle functions@~lint: Args: [ '/d /s /c', 'eslint .' ]
11 silly lifecycle functions@~lint: Returned: code: 1  signal: null
12 info lifecycle functions@~lint: Failed to exec lint script
13 verbose stack Error: functions@ lint: `eslint .`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:285:16)
13 verbose stack     at emitTwo (events.js:126:13)
13 verbose stack     at EventEmitter.emit (events.js:214:7)
13 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at emitTwo (events.js:126:13)
13 verbose stack     at ChildProcess.emit (events.js:214:7)
13 verbose stack     at maybeClose (internal/child_process.js:925:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
14 verbose pkgid functions@
15 verbose cwd C:\Users\User\Desktop\pushcloud
16 verbose Windows_NT 10.0.16299
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "--prefix" "C:\\Users\\User\\Desktop\\pushcloud\\functions" "run" "lint"
18 verbose node v8.9.4
19 verbose npm  v5.6.0
20 error code ELIFECYCLE
21 error errno 1
22 error functions@ lint: `eslint .`
22 error Exit status 1
23 error Failed at the functions@ lint script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

代码似乎有问题,因为默认的Hello from Firebase!部署成功了

编辑:

如果以firebase.json格式从\"%RESOURCE_DIR%\""%RESOURCE_DIR%"进行编辑,则

  

错误:加载firebase.json时出错:意外令牌'%'   “ npm --prefix”%RESOURCE_DIR%“运行皮棉”

如果我从firebase.json中删除行并在终端中运行npm --prefix "%RESOURCE_DIR%" run lint

npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\User\Desktop\pushcloud\%RESOURCE_DIR%\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\User\AppData\Roaming\npm-cache\_logs\2018-07-13T11_33_25_593Z-debug.log 

但当%RESOURCE_DIR%位于功能目录中时,目录文件夹与etc一起以package.json的形式存在。如果我将其重新定位到%RESOURCE_DIR%

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions@ lint: `eslint .`
npm ERR! Exit status 1
npm ERR! Failed at the functions@ lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\User\AppData\Roaming\npm-cache\_logs\2018-07-13T11_50_15_739Z-debug.log

并带有$ firebase deploy --only functions

C:\Users\User\Desktop\pushcloud\functions\index.js
   9:5   error    Expected catch() or return                  promise/catch-or-return
   9:80  error    Each then() should return a value or throw  promise/always-return
  12:9   error    Expected catch() or return                  promise/catch-or-return
  12:9   warning  Avoid nesting promises                      promise/no-nesting
  33:24  warning  Avoid nesting promises                      promise/no-nesting
  33:24  warning  Avoid nesting promises                      promise/no-nesting
  33:77  error    Each then() should return a value or throw  promise/always-return

✖ 7 problems (4 errors, 3 warnings)

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions@ lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions@ lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\User\AppData\Roaming\npm-cache\_logs\2018-07-13T11_51_50_784Z-debug.log
Error: functions predeploy error: Command terminated with non-zero exit code1

1 个答案:

答案 0 :(得分:1)

您的部署前标志npm --prefix \"%RESOURCE_DIR%\" run lint引起了您的问题。

如果您在终端中运行npm --prefix "%RESOURCE_DIR%" run lint,它是否可以正确运行且没有错误?

如果您从firebase.json中删除该行,则该行应该没有问题。

  

编辑

检查收到的错误消息,它会为您找到答案。您的代码linter失败了,您需要先修复这些错误,然后才能进行部署。

9:5   error    Expected catch() or return                  promise/catch-or-return
9:80  error    Each then() should return a value or throw  promise/always-return
12:9   error    Expected catch() or return                  promise/catch-or-return
12:9   warning  Avoid nesting promises                      promise/no-nesting
33:24  warning  Avoid nesting promises                      promise/no-nesting
33:24  warning  Avoid nesting promises                      promise/no-nesting
33:77  error    Each then() should return a value or throw  promise/always-return

我快速浏览了您的代码,并且我认为我已经清理了它。另外,您无需承诺processtokens,它是一个同步功能。

const functions = require('firebase-functions');
var admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);
var wrotedata;
exports.Pushtrigger = functions.database.ref('/messages/{messageId}').onWrite((event) => {
    wrotedata = event.data.val();

    return admin.database().ref('/pushtokens')
      .orderByChild('uid')
      .once('value')
      .then((alltokens) => {
        var rawtokens = alltokens.val();
        var tokens = [];

        var processedtokens = this.processtokens(rawtokens);

        for (var token in processedtokens) {
            tokens.push(token.devtoken);
        }

        var payload = {
            "notification": {
                "title": "Notification title",
                "body": "Notification body",
                "sound": "default",
                "click_action": "FCM_PLUGIN_ACTIVITY",
                "icon": "fcm_push_icon"
            },
            "data": {
                "message": "value1",
                "sendername": "value2"
            }
        };

        return admin.messaging().sendToDevice(tokens, payload).then((response) => {
            console.log('Push notifications');
        }).catch((err) => {
            console.log(err);
        })        
    })
})

function processtokens(rawtokens) {
    var processedtokens = []
    for (token in rawtokens) {
        processedtokens.push(rawtokens[token]);
    }

    return processdatatokens;
}