REST API using Express with Firebase cloud functions


To install firebase tools

npm install -g firebase-tools


To log in to the firebase account and initialize it

firebase login
firebase init

Install express and body-parser

cd functions
npm install express body-parser --save


Install index.ts

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin'
import * as express from 'express'
import * as bodyParser from 'body-parser'

admin.initializeApp(functions.config().firebase);

const app=express()
const main=express()

main.use('/Myapi',app)
main.use(bodyParser.json())
main.use(bodyParser.urlencoded({extended:false}))

const db=admin.firestore()
export const webApi=functions.https.onRequest(main)


interface Product 
{
    productName:string,
    productPrice:string
}

app.post('/saveProduct',async(req,res)=>{

const product:Product={

    productName:"Bag",
    productPrice:"1000"
}

await db.collection("productOnSale").add(product)

})

Comments

  1. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. fix 'main.use('/Myapi',app)' as 'main.use('/',app)''
      otherwise change the url as 'https://....cloudfunctions.net/webApi/Myapi/saveProduct'

      Delete

Post a Comment