{
    "componentChunkName": "component---src-templates-blog-post-js",
    "path": "/restapi-using-deno-oak-mongodb/",
    "result": {"data":{"site":{"siteMetadata":{"title":"CrewCode Solutions"}},"markdownRemark":{"id":"6d904096-d929-5403-a8d8-150a4d45b491","excerpt":"In this article i will explain you step by step to setup REST Api with deno, oak and mongodb and iam using macOS operating system but procedure is same for…","html":"<p>In this article i will explain you step by step to setup REST Api with deno, oak and mongodb and iam using macOS operating system but procedure is same for Windows and Linux users</p>\n<h4>Step 1: Install deno</h4>\n<p>For macOS and Linux user use below command</p>\n<pre><code class=\"language-js\">curl -fsSL https://deno.land/install.sh | sh\n</code></pre>\n<p>For Window user Using Powershell use below command</p>\n<pre><code class=\"language-js\">iwr https://deno.land/install.ps1 -useb | iex\n</code></pre>\n<p><img src=\"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/Developing-REST-Api-using-Deno-Oak-MongoDB-1.png\" alt=\"deno\"></p>\n<h3>Step 2: Download Visual Studio Code and install extension deno</h3>\n<p><img src=\"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/Developing-REST-Api-using-Deno-Oak-MongoDB-2.png\" alt=\"deno-visual-studio\"></p>\n<h3>Step 3: Create app.ts file under root path of your deno project</h3>\n<p>Advantage of using deno is we don't need to install packages instead we call standard deno library</p>\n<p>Inside your app.ts file copy paste below code this is the main file for your deno rest api</p>\n<pre><code class=\"language-js\">import { Application } from \"https://deno.land/x/oak/mod.ts\";\n\nimport notesRoutes from \"./routes/notes.ts\";\n\nimport { connect } from \"./helpers/db.ts\";\n\nconnect();\n\nconst app = new Application();\n\napp.use(async (ctx, next) => {\n  console.log(\"Middleware!\");\n  await next();\n});\n\napp.use(async (ctx, next) => {\n  ctx.response.headers.set(\"Access-Control-Allow-Origin\", \"*\");\n  ctx.response.headers.set(\n    \"Access-Control-Allow-Methods\",\n    \"GET,POST,PUT,DELETE\"\n  );\n  ctx.response.headers.set(\"Access-Control-Allow-Headers\", \"Content-Type\");\n  await next();\n});\n\napp.use(notesRoutes.routes());\napp.use(notesRoutes.allowedMethods());\n\nawait app.listen({ port: 3000 });\n</code></pre>\n<h3>Step 4: Create controllers folder under root path of your project folder and under that folder create notes.ts file</h3>\n<p>This is the controller file where you will be writing all the logic for GET, POST, PUT , DELETE Rest API methods</p>\n<p>Copy paste below code in you controller file</p>\n<pre><code class=\"language-js\">import { ObjectId } from \"https://deno.land/x/mongo@v0.29.4/mod.ts\";\nimport { getDb } from \"../helpers/db.ts\";\nimport { Notes } from \"../interfaces/notes.ts\";\n\nexport default {\n  getAllNotes: async ({ response }: { response: any }) => {\n    const notes = await getDb().collection(\"notes\").find({}).toArray();\n    response.status = 201;\n    response.body = { message: \"All Notes!\", notes: notes };\n  },\n  createNotes: async ({\n    request,\n    response,\n  }: {\n    request: any;\n    response: any;\n  }) => {\n    const data = await request.body().value;\n    const newNotes: Notes = {\n      text: data.text,\n    };\n\n    await getDb().collection(\"notes\").insertOne(newNotes);\n    response.status = 201;\n    response.body = { message: \"Created notes!\", todo: newNotes };\n  },\n  getById: async ({\n    params,\n    response,\n  }: {\n    params: { noteId: string };\n    response: any;\n  }) => {\n    const tid = params.noteId!;\n    const notes = await getDb()\n      .collection(\"notes\")\n      .findOne({ _id: new ObjectId(tid) });\n    response.status = 201;\n    response.body = { message: \"New notes!\", notes: notes };\n  },\n  updateNoteById: async ({\n    params,\n    request,\n    response,\n  }: {\n    params: { noteId: string };\n    request: any;\n    response: any;\n  }) => {\n    const tid = params.noteId!;\n    const data = await request.body().value;\n\n    const notes = await getDb()\n      .collection(\"notes\")\n      .updateOne({ _id: new ObjectId(tid) }, { $set: { text: data.text } });\n    response.status = 201;\n    response.body = { message: \"Updated notes\", notes: notes };\n  },\n  deleteNoteById: async ({\n    params,\n    response,\n  }: {\n    params: { noteId: string };\n    response: any;\n  }) => {\n    const tid = params.noteId!;\n\n    const notes = await getDb()\n      .collection(\"notes\")\n      .deleteOne({ _id: new ObjectId(tid) });\n\n    response.status = 201;\n    response.body = { message: \"Deleted notes\", notes: notes };\n  },\n};\n</code></pre>\n<h3>Step 5: Create interface/types</h3>\n<p>As we clearly know typescript do check types strictly that is what that advantage we have over using typescript so we need to\neither create interface or types for defining the types of data we are passing in request and getting in request</p>\n<p><strong><em>Create interfaces folder under root path of your project and inside that folder create notes.ts file</em></strong> and copy paste below code inside notes.ts file</p>\n<pre><code class=\"language-js\">export interface Notes {\n  text: string;\n}\n</code></pre>\n<h3>Step 6: Create routes folder under root path of your project folder and under that folder create notes.ts file</h3>\n<p>This is the route file for your deno Rest API here you will be defining paths for your UPDATE, DELETE, GET, POST request</p>\n<p>Copy paste below code in the file</p>\n<pre><code class=\"language-js\">import { Router } from \"https://deno.land/x/oak/mod.ts\";\nconst router = new Router();\n\nimport notesController from \"../controllers/notes.ts\";\n\nrouter.get(\"/notes\", notesController.getAllNotes);\n\nrouter.post(\"/notes\", notesController.createNotes);\n\nrouter.put(\"/notes/:noteId\", notesController.updateNoteById);\n\nrouter.get(\"/notes/:noteId\", notesController.getById);\n\nrouter.delete(\"/notes/:noteId\", notesController.deleteNoteById);\n\nexport default router;\n</code></pre>\n<h3>Step 7: Create MongoDB database configuration file</h3>\n<p><strong><em>Create helpers folder under root path of your project inside helpers folder create db.ts file</em></strong> inside db.ts file copy paste below code</p>\n<pre><code class=\"language-js\">import {\n  MongoClient,\n  Database,\n} from \"https://deno.land/x/mongo@v0.29.4/mod.ts\";\n\nlet db: Database;\n\nexport async function connect() {\n  const client = new MongoClient();\n  await client.connect(\"mongodb://localhost:27017\");\n  console.log(\"Database connected\");\n  db = client.database(\"notes\");\n}\n\nexport function getDb() {\n  return db;\n}\n</code></pre>\n<h3>Complete folder structure, run the project, test the API</h3>\n<p><strong><em>By default deno deosn't allow permission for anything</em></strong> this is extra feature which deno has introduced so in order to allow permission we need to mention in the command itself</p>\n<p>Copy paste below command and run in your terminal by navigating to project folder</p>\n<pre><code class=\"language-js\">deno run --allow-net --allow-read --allow-write app.ts\n</code></pre>\n<p><img src=\"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/Developing-REST-Api-using-Deno-Oak-MongoDB-3.png\" alt=\"deno-run\"></p>\n<p><img src=\"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/Developing-REST-Api-using-Deno-Oak-MongoDB-4.png\" alt=\"postman-link\"></p>","fields":{"slug":"/restapi-using-deno-oak-mongodb/"},"frontmatter":{"title":"Developing REST Api using Deno, Oak and MongoDB","date":"April 30, 2023","description":"In this article i will explain you step by step to setup REST Api with Deno, Oak and MongoDB","bannerimage":"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/RestAPI.jpg"}},"previous":{"fields":{"slug":"/react-tutorial-working-with-redux-toolkit-with-saga/"},"frontmatter":{"title":"React tutorial working with redux toolkit with saga in typescript","date":"April 26, 2023","bannerimage":"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/redux-toolkit.jpeg"}},"next":{"fields":{"slug":"/saving-data-to-google-spreadheet-node/"},"frontmatter":{"title":"Saving data to google spreadsheet in node js application","date":"May 01, 2023","bannerimage":"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/google-spreadheet-node.jpeg"}}},"pageContext":{"id":"6d904096-d929-5403-a8d8-150a4d45b491","previousPostId":"cf94ca75-725d-52ee-b2ab-71f7aa5fd158","nextPostId":"d2c3f700-da09-536c-bca4-5bb8c0cd346e"}},
    "staticQueryHashes": ["3860684146"]}