loader

previous:Build a free Todo REST API with ECMAScript 6 and MongoDB

Create Namespace : todonamespace

Create function : gettodoapi

add uri environment variables

DB_URI=mongodb+srv://todoapi:password@cluster0.kppad.mongodb.net/todo?retryWrites=true&w=majority

add mongoose dependencies

Create a Todo Type

const todoSchema = new Schema(
    {
        name: {
            type: String,
            required: true,
        },
        description: {
            type: String,
            required: true,
        },
        status: {
            type: Boolean,
            required: true,
        },
    },
    { timestamps: true }
);
const Todo = mongoose.model('Todo', todoSchema);

Adding the database connection

The process of connecting to MongoDB is twofold. We need to create a dynamic way of creating the connection but also make sure to re-use the same connection if it’s available. We’ll start slow.

import { Schema } from 'mongoose';
import mongoose from "mongoose";

mongoose.Promise = global.Promise;
let isConnected;
const connectToDatabase = () => {
    if (isConnected) {
        console.log('=> using existing database connection');
        return Promise.resolve();
    }
    console.log('=> using new database connection');
    return mongoose.connect(process.env.DB_URI)
        .then(db => {
            isConnected = db.connections[0].readyState;
        });
};

add Function to execute

export const indexgettodo = (event, context) => {

    return connectToDatabase().then(() => {

        return Todo.find();

    });
};

import { Schema } from 'mongoose';
import mongoose from "mongoose";

mongoose.Promise = global.Promise;
let isConnected;
const connectToDatabase = () => {
    if (isConnected) {
        console.log('=> using existing database connection');
        return Promise.resolve();
    }
    console.log('=> using new database connection');
    return mongoose.connect(process.env.DB_URI)
        .then(db => {
            isConnected = db.connections[0].readyState;
        });
};


const todoSchema = new Schema(
    {
        name: {
            type: String,
            required: true,
        },

        description: {
            type: String,
            required: true,
        },

        status: {
            type: Boolean,
            required: true,
        },
    },
    { timestamps: true }
);
const Todo = mongoose.model('Todo', todoSchema);

export const indexgettodo = (event, context) => {

    return connectToDatabase().then(() => {

        return Todo.find();

    });
};

Deploy function

Open up your REST client of choice, Postman, Insomnia or whatever you prefer, and let’s get on with the testing.

x-apikey-header

API keys for authorization. An API key is a token that a client provides when making API calls. to get your x-apikey-header,go to detail namespace page