In my "/yourPage" route, my handler is trying to fetch "/api/joke" from my local database. I get "URL not found" error. Since Fresh is server rendered, I'd like to get all the data I need when loading the first time.
This works fine when fetching after initial load (like with a button).
As per its documentation, it should work fine, and does for any API that is not in its own repository.
Any way I can make this work? Am I thinking of this the wrong way?
The fetch inside my handler:
routes/yourPage.ts
export const handler: Handlers = {
async GET(req, ctx) {
const joke = await getJokes()
return ctx.render(joke);
},
};
/routes/api/joke.ts
const JOKES = [
"Why do Java developers often wear glasses? They can't C#.",
"A SQL query walks into a bar, goes up to two tables and says “can I join you?”",
];
export const handler = (_req: Request, _ctx: HandlerContext): Response => {
const randomIndex = Math.floor(Math.random() * JOKES.length);
const body = JOKES[randomIndex];
return new Response(body);
};
Pretty old post, but this is the first StackOverflow Google result when you try to search for API calling in Fresh Framework.
I am assuming you imported inside routes/yourPage.ts the handler from /routes/api/joke.ts as this:
import { handler as getJokes } from "./api/joke.ts";
Inside routes/yourPage.ts you also have to extract the text/json from the response before using it:
export const handler: Handlers = {
async GET(_req, _ctx) {
const response = getJokes(_req, _ctx);
const jokeText = await response.text();
return _ctx.render(jokeText);
},
};
Then you can use the response in your page as:
export default function Home({ data }: PageProps) { //...
Documentation here:
https://fresh.deno.dev/docs/getting-started/fetching-data
In my Expo (react-native) application, I want to do the upload task even if the application is in the background or killed.
the upload should be done to firebase storage, so we don't have a REST API.
checked out the Expo task manager library, but I could not figure out how it should be done. is it even possible to achieve this goal with Expo? is the TaskManager the correct package for this task?
there are only some Expo packages that could be registered as a task (e.g. backgroundFetch), and it is not possible to register a custom function (in this case uploadFile method).
I even got more confused as we should enable add UIBackgroundModes key for iOS but it only has audio,location,voip,external-accessory,bluetooth-central,bluetooth-peripheral,fetch,remote-notification,processing as possible values.
I would appreciate it if you can at least guide me on where to start or what to search for, to be able to upload the file even if the app is in the background is killed/terminated.
import { getStorage, ref, uploadBytes } from "firebase/storage";
const storage = getStorage();
const storageRef = ref(storage, 'videos');
const uploadFile = async (file)=>{
// the file is Blob object
await uploadBytes(storageRef, file);
}
I have already reviewed react-native-background-fetch, react-native-background-upload, react-native-background-job . upload should eject Expo, job does not support iOS, and fetch is a fetching task designed for doing task in intervals.
if there is a way to use mentioned libraries for my purpose, please guide me :)
to my understanding, the Firebase Cloud JSON API does not accept files, does it ? if so please give me an example. If I can make storage json API work with file upload, then I can use Expo asyncUpload probably without ejecting.
I have done something similar like you want, you can use expo-task-manager and expo-background-fetch. Here is the code as I used it. I Hope this would be useful for you.
import * as BackgroundFetch from 'expo-background-fetch';
import * as TaskManager from 'expo-task-manager';
const BACKGROUND_FETCH_TASK = 'background-fetch';
const [isRegistered, setIsRegistered] = useState(false);
const [status, setStatus] = useState(null);
//Valor para que se ejecute en IOS
BackgroundFetch.setMinimumIntervalAsync(60 * 15);
// Define the task to execute
TaskManager.defineTask(BACKGROUND_FETCH_TASK, async () => {
const now = Date.now();
console.log(`Got background fetch call at date: ${new Date(now).toISOString()}`);
// Your function or instructions you want
return BackgroundFetch.Result.NewData;
});
// Register the task in BACKGROUND_FETCH_TASK
async function registerBackgroundFetchAsync() {
return BackgroundFetch.registerTaskAsync(BACKGROUND_FETCH_TASK, {
minimumInterval: 60 * 15, // 1 minutes
stopOnTerminate: false, // android only,
startOnBoot: true, // android only
});
}
// Task Status
const checkStatusAsync = async () => {
const status = await BackgroundFetch.getStatusAsync();
const isRegistered = await TaskManager.isTaskRegisteredAsync(
BACKGROUND_FETCH_TASK
);
setStatus(status);
setIsRegistered(isRegistered);
};
// Check if the task is already register
const toggleFetchTask = async () => {
if (isRegistered) {
console.log('Task ready');
} else {
await registerBackgroundFetchAsync();
console.log('Task registered');
}
checkStatusAsync();
};
useEffect(() => {
toggleFetchTask();
}, []);
Hope this isn't too late to be helpful.
I've been dealing with a variety of expo <-> firebase storage integrations recently, and here's some info that might be helpful.
First, I'd recommend not using the uploadBytes / uploadBytesResumable methods from Firebase. This Thread has a long ongoing discussion about it, but basically it's broken in v9. Maybe in the future the Firebase team will solve the issues, but it's pretty broken with Expo right now.
Instead, I'd recommend either going down the route of writing a small Firebase function that either gives a signed-upload-url or handles the upload itself.
Basically, if you can get storage uploads to work via an http endpoint, you can get any kind of upload mechanism working. (e.g. the FileSystem.uploadAsync() method you're probably looking for here, like #brentvatne pointed out, or fetch, or axios. I'll show a basic wiring at the end).
Server Side
Option 1: Signed URL Upload.
Basically, have a small firebase function that returns a signed url. Your app calls a cloud function like /get-signed-upload-url , which returns the url, which you then use. Check out: https://cloud.google.com/storage/docs/access-control/signed-urls for how you'd go about this.
This might work well for your use case. It can be configured just like any httpsCallable function, so it's not much work to set up, compared to option 2.
However, this doesn't work for the firebase storage / functions emulator! For this reason, I don't use this method, because I like to intensively use the emulators, and they only offer a subset of all the functionalities.
Option 2: Upload the file entirely through a function
This is a little hairier, but gives you a lot more fidelity over your uploads, and will work on an emulator! I like this too because it allows doing upload process within the endpoint execution, instead of as a side effect.
For example, you can have a photo-upload endpoint generate thumbnails, and if the endpoint 201's, then you're good! Rather than the traditional Firebase approach of having a listener to cloud storage which would generate thumbnails as a side effect, which then has all kinds of bad race conditions (checking for processing completion via exponentiational backoff? Gross!)
Here are three resources I'd recommend to go about this approach:
https://cloud.google.com/functions/docs/writing/http#multipart_data
https://github.com/firebase/firebase-js-sdk/issues/5848
https://github.com/mscdex/busboy
Basically, if you can make a Firebase cloud endpoint that accepts a File within formdata, you can have busboy parse it, and then you can do anything you want with it... like upload it to Cloud Storage!
an outline of this:
import * as functions from "firebase-functions";
import * as busboy from "busboy";
import * as os from "os";
import * as path from "path";
import * as fs from "fs";
type FieldMap = {
[fieldKey: string]: string;
};
type Upload = {
filepath: string;
mimeType: string;
};
type UploadMap = {
[fileName: string]: Upload;
};
const MAX_FILE_SIZE = 2 * 1024 * 1024; // 2MB
export const uploadPhoto = functions.https.onRequest(async (req, res) => {
verifyRequest(req); // Verify parameters, auth, etc. Better yet, use a middleware system for this like express.
// This object will accumulate all the fields, keyed by their name
const fields: FieldMap = {};
// This object will accumulate all the uploaded files, keyed by their name.
const uploads: UploadMap = {};
// This will accumulator errors during the busboy process, allowing us to end early.
const errors: string[] = [];
const tmpdir = os.tmpdir();
const fileWrites: Promise<unknown>[] = [];
function cleanup() {
Object.entries(uploads).forEach(([filename, { filepath }]) => {
console.log(`unlinking: ${filename} from ${path}`);
fs.unlinkSync(filepath);
});
}
const bb = busboy({
headers: req.headers,
limits: {
files: 1,
fields: 1,
fileSize: MAX_FILE_SIZE,
},
});
bb.on("file", (name, file, info) => {
verifyFile(name, file, info); // Verify your mimeType / filename, etc.
file.on("limit", () => {
console.log("too big of file!");
});
const { filename, mimeType } = info;
// Note: os.tmpdir() points to an in-memory file system on GCF
// Thus, any files in it must fit in the instance's memory.
console.log(`Processed file ${filename}`);
const filepath = path.join(tmpdir, filename);
uploads[filename] = {
filepath,
mimeType,
};
const writeStream = fs.createWriteStream(filepath);
file.pipe(writeStream);
// File was processed by Busboy; wait for it to be written.
// Note: GCF may not persist saved files across invocations.
// Persistent files must be kept in other locations
// (such as Cloud Storage buckets).
const promise = new Promise((resolve, reject) => {
file.on("end", () => {
writeStream.end();
});
writeStream.on("finish", resolve);
writeStream.on("error", reject);
});
fileWrites.push(promise);
});
bb.on("close", async () => {
await Promise.all(fileWrites);
// Fail if errors:
if (errors.length > 0) {
functions.logger.error("Upload failed", errors);
res.status(400).send(errors.join());
} else {
try {
const upload = Object.values(uploads)[0];
if (!upload) {
functions.logger.debug("No upload found");
res.status(400).send("No file uploaded");
return;
}
const { uploadId } = await processUpload(upload, userId);
cleanup();
res.status(201).send({
uploadId,
});
} catch (error) {
cleanup();
functions.logger.error("Error processing file", error);
res.status(500).send("Error processing file");
}
}
});
bb.end(req.rawBody);
});
Then, that processUpload function can do anything you want with the file, like upload it to cloud storage:
async function processUpload({ filepath, mimeType }: Upload, userId: string) {
const fileId = uuidv4();
const bucket = admin.storage().bucket();
await bucket.upload(filepath, {
destination: `users/${userId}/${fileId}`,
{
contentType: mimeType,
},
});
return { fileId };
}
Mobile Side
Then, on the mobile side, you can interact with it like this:
async function uploadFile(uri: string) {
function getFunctionsUrl(): string {
if (USE_EMULATOR) {
const origin =
Constants?.manifest?.debuggerHost?.split(":").shift() || "localhost";
const functionsPort = 5001;
const functionsHost = `http://${origin}:${functionsPort}/{PROJECT_NAME}/${PROJECT_LOCATION}`;
return functionsHost;
} else {
return `https://{PROJECT_LOCATION}-{PROJECT_NAME}.cloudfunctions.net`;
}
}
// The url of your endpoint. Make this as smart as you want.
const url = `${getFunctionsUrl()}/uploadPhoto`;
await FileSystem.uploadAsync(uploadUrl, uri, {
httpMethod: "POST",
uploadType: FileSystem.FileSystemUploadType.MULTIPART,
fieldName: "file", // Important! make sure this matches however you want bussboy to validate the "name" field on file.
mimeType,
headers: {
"content-type": "multipart/form-data",
Authorization: `${idToken}`,
},
});
});
TLDR
Wrap Cloud Storage in your own endpoint, treat it like a normal http upload, everything plays nice.
I have an express route and I want to send back the result of a fetch to my pug template. I know my fetch URL works as I have checked it with postman and the data comes back as it should. I would like to store the fetch of the result to the variable called weather at the bottom of the route. My template looks for this variable to exist before adding weather to the template
I have also logged my form data to make sure the form is sending the data to my express server
I get this error in my command console when logging the return:
Promise { <pending> }
(node:18060) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'json' of undefined
I think the issue must be with my promise structure or perhaps it has to do with CORS not being enabled in my app? I'm not getting any errors and I'm hoping someone might have an answer for me??
router.post("/", async(req, res, next)=>{
console.log(req.body.selectedCity)
console.log(req.body.selectedState)
console.log(req.body.selectedZip)
var result = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${req.body.selectedCity}&units=imperial&appid=${apiKey}`)
.then(function(result) {
console.log(result.json())
})
.then((result)=>{
console.log(result.json())
res.render('index', {states:[
{
id:"none",
name:"choose"
},
{
id:"OH",
name:"Ohio"
},
{
id:"UT",
name:"Utah"
},
{
id:"VT",
name:"Vermont"
},
{
id:"VA",
name:"Virginia"
},
{
id:"WA",
name:"Washington"
},
{
id:"WV",
name:"West Virginia"
},
{
id:"WI",
name:"Wisconsin"
},
{
id:"WY",
name:"Wyoming"
}
],weather:result})
})
});
You have an uncorrect syntax on async/await.
You do not use .then in async/await but you just await the promise and store the result in a variable.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
var result = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${req.body.selectedCity}&units=imperial&appid=${apiKey}`)
.then(function(result) {
console.log(result.json())
})
.then((result)=>{
console.log(result.json())
res.render [...]
Becomes:
const result = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${req.body.selectedCity}&units=imperial&appid=${apiKey}`);
console.log(result.json())
res.render [...]
Try and avoid var as it may lead to unexpected behavior.
Try using axios as a fetch library, it's much cleaner than fetch.
https://www.npmjs.com/package/axios
This way it's just const result = await axios.get([...]
This should be structured this way instead -
fetch('url')
.then(result=>result.json)
.then(result=>res.render())
You should also remove async keyword from the callback function provide to router.post.
Неllo! I need help.
I have these data - tree terms in the store.
How to write a post-request to the server to sync terms in Vue components methods, when the mockdata is off.
P.S. Нow can use Axios?
methods: {
onTermCreate(newTerm) {
const actionName = this.getModuleActionName('term', ACTIONS_NAMES.CREATE_TERM);
this.$store.dispatch(actionName, newTerm).then(() => {
// TODO add post request to sync terms state with server, then reset form //
this.showPostRequestData();
this.resetForm();
})
},
addNewDataToExistingTerm(existingTerm, newTerm) {
existingTerm.parents.push(newTerm);
const actionName = this.getModuleActionName('term', ACTIONS_NAMES.UPDATE_TERM);
this.$store.dispatch(actionName, existingTerm).then(() => {
// TODO add post request to sync terms state with server, then reset form //
this.showPostRequestData();
this.resetForm();
})
}
}
Put all your API calls inside Actions in your Vuex store. This way every change that gets committed to your state only comes from inside the store and makes it easier for you to debug and make the code easier to understand.
Now to use axios you should do something like this:
state = {
//
},
getters = {
//
},
mutations = {
SET_TERM : (state,payload) => {
state.term = payload
}
},
actions = {
CREATE_TERM : async (context,payload) => {
let { data } = await Axios.get('/path/to/api/')
context.commit('SET_TODO',data)
}
}
Please read this awesome article for more explanations and details.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm a beginner in Node (and generally all back-end web development), and I have started to write a RESTful API in Node. There are a few things I'm trying to get my head around.
My application uses Express and Mongoose, and I am using the express-resource module to easily create my CRUD routes for the API resources. But there are a couple of things I am unhappy about, and think I could do better.
The first is Mongoose. If I want to write tests for my API, I have no way of stubbing Mongoose to force it to in memory data. All of the tutorials out there seem to point to Mongoose, however, and I'm really not sure what I should be using.
Secondly, my resource seems to have a lot of boilerplate code. Is this really the best way to create a RESTful API in Node.js? Are there other modules that will help me to create my CRUD routes? I believe there are ways you can create CRUD routes right from your schema, without anymore code, but I'm really not sure how.
I have seen projects out there such as Tower.js and CompoundJS (formally RailwayJS) that seem to be these comprehensive solutions that solve much more than my issues here. Perhaps I should be using them, but I really only want the Node.js application to be an API and nothing more. I am dealing with the front-end independently of the API.
To provide some context, here is my current situation. Currently, I have a model defined in Mongoose:
var mongoose = require('mongoose')
, Schema = mongoose.Schema
, Link
var LinkSchema = new Schema({
uri: String,
meta: {
title: String,
desc: String
},
shares: [{
uid: Schema.Types.ObjectId,
date: Date,
message: String
}]
})
Link = module.exports = mongoose.model('Link')
Next, I define the controllers for the CRUD routes:
var mongoose = require('mongoose')
, _ = require('underscore')
, Link = mongoose.model('Link')
exports.load = function (req, id, fn) {
Link.findById(req.params.link, function (err, link) {
if (err) {
return res.send(err)
}
fn(null, link)
})
}
exports.index = function (req, res) {
var filterByUser = req.query.user ? { 'shares.uid': req.query.user } : {}
Link.find(filterByUser, function (err, links) {
if (err) {
return res.send(err)
}
res.send(links)
})
}
exports.create = function (req, res) {
var link = new Link(req.body)
link.save(function (err) {
if (err) {
// TODO: send 404
return res.send(err)
}
res.send(link)
})
}
exports.show = function (req, res) {
res.send(req.link)
}
exports.update = function (req, res) {
req.link = _(req.link).extend(req.body)
req.link.save(function (err, link) {
if (err) {
return res.send(err)
}
res.send(link)
})
}
exports.patch = exports.update
exports.destroy = function (req, res) {
req.link.remove(function (err) {
if (err) {
return res.send(err)
}
res.send()
})
}
Finally, I use the express-resource module to map these controllers to the necessary CRUD routes on top of the Express app.
app.resource('api/links', require('../resources/links'))
You should look into restify
If you want to use express, you can also check out this project that I made -- called node-restful.
This library seems to be much more mature and have more features though: https://github.com/jspears/mers
Strongloop Loopback seeems to be another good alternative for generating Node/MongoDB APIs. It can also generate mocha tests too.
Take a look at Hapi its a configuration-centric framework for building web applications and APIs its used as restful service.
Other options are sails.js and actionhero
Strapi is a new (2015) framework.
The admin interface on their website allows you to create an API and specify relationships between models. (As can be seen in their introduction video.)
However it is designed to run on the Koa server, not on Express.
I recommend Baucis + Express. Thousands of users, model-driven design based on Mongoose, very flexible, spec-compliant, HATEOAS/Level 3 ready. Fits all my needs perfectly. But then, I'm the author :) https://github.com/wprl/baucis
Check this out:
With Feathers you can build prototypes in minutes and production ready real-time backends and REST APIs in days. Seriously.
Here is the issues about the frameworks nowadays.
When you come here from google searching "best", "fastest" framework blah, blah, people will drop a line says "Hey, you should try this sails.js, feathers, Derby etc..."
Ok The question is:
- Are you just for fun with those frameworks - if yes, you can easily get a list of frameworks and then start to benchmark them whatsoever.
I am assuming most of people are "I want to build a product, build a site can make money in the future, or at least it will become popular";
Ok, all you search keywords and attentions here is wrong, try to search "production ready", "enterprise ready", "case study" those keywords then, or maybe go to indeed.com and search node.js, further dig out what node.js framework most companies using, the answer maybe just simply say "express".
if so, From node.js stack, The frameworks will pretty much be narrowed down a few of them: Hapi, Strongloop, or even not popular one Mojito from Yahoo
For Those frameworks at least you can tell - "They are really production or enterprise ready" - cos' they have been using form Walmart, from Yahoo, from other big giants from some time, some even for couple of years.
Can this explain why Ruby on rails and Django still dominate the full stack framework markets? even you see lots of "cool" frameworks keeping on coming to the market, Meteor, Sails.js, Go's Revel, Java's Play Spark whatever you can name - It doesn't mean these frameworks worse than the two, just mean they need time to win the market.
Another problems lots of the current frameworks are a kind of all-in-one, clone of "Ror"; From the end user's prospect, They just need a thing to help them get things done, need productive, need something to work from the begin to the end, like Ruby on Rails, like MacOS, like windows, like anything itself which has been tested by the time, has been daily used by people.
I've been using Express to build my RESTful APIs on Node.js and with the addition of Router in Express 4, it's even easier to structure it. It's detailed here http://www.codekitchen.ca/guide-to-structuring-and-building-a-restful-api-using-express-4/
Try https://hivepod.io/ and generate your example in a full MEAN stack. Hivepod builds on top of BaucisJS + ExpressJS + MongoDB + AngularJS.
Disclaimer: I work building Hivepod.
Have a look into this link
This project is build using the same project archutecture which is followed by ASP.Net WebApi 2.0. That means it will be having controllers, authentication mechanism etc. to start with. All you need to do is create your own controllers.
I'm surprised no-one mentioned Nodal.
From the website:
Nodal is a web server for Node.js, optimized for building API services quickly and efficiently.
Boasting its own opinionated, explicit, idiomatic and highly-extensible framework, Nodal takes care of all of the hard decisions for you and your team. This allows you to focus on creating an effective product in a short timespan while minimizing technical debt
It's actively maintained, has 3800+ stars on Github (at the time of writing), has a command-line tool built-in to generate boilerplate code, and overall gets the job done quickly.
This is a sample to perform CRUD operations in a library system
var schema=require('../dbSchema');
var bookmodel=schema.model('book');
exports.getBooks = function (req,res) {
bookmodel.find().exec().then((data)=>{
res.send(data)
}).catch((err)=>{
console.log(err);
});
};
exports.getBook = function (req,res) {
var bkName=req.params.Author;
bookmodel.find({Name:bkName}).exec().then((data)=>{
res.send(data)
}).catch((err)=>{
console.log(err);
});
};
exports.getAutBooks = function (req,res) {
bookmodel.find({},'Author').then((data)=>{
res.send(data);
}).catch((err)=>{
console.log(err);
});
};
exports.deleteBooks=function(req,res){
var bkName=req.params.name;
bookmodel.remove({Name:bkName}).exec().then((data)=>{
res.status(200);
console.log(bkName);
}).catch((err)=>{
console.log(err);
});
};
exports.addBooks=function(req,res){
var newBook=new bookmodel({
Name:req.body.Name,
ISBN:req.body.ISBN,
Author:req.body.Author,
Price:req.body.Price,
Year:req.body.Year,
Publisher:req.body.Publisher
});
newBook.save().then(()=>{
res.status(201);
}).catch((err)=>{
console.log(err);
});
};
I am a big fan of express and I've been using it to build RESTful APIs on Node.js which are easier to build. However, when our application started growing, we ended in a situation where express structure did not scale well and with more code splitting around, it was harder for us to maintain.
I am from C#/Java background where SOLID principles are heavily used. Frameworks like Java Spring / C# WebAPI are proven to create enterprise level applications.
I wanted to have a framework where I can reuse my existing C#/Java skills (reuse I mean MVC architecture, OOPS, SOLID, DI, Mocks ... yeah, strong typing). Unfortunately, I did not find a framework which meets my requirements (It should have less learning curve, minimalist codebase size, completely express compatible).
What do I mean by completely express compatible? Whatever express does, I must be able to do it even If I use a framework on top of it, when I have looked into Strongloop Loopback it was pretty good to use but It had a lot of documentation to go through and the frameworks are coupled, not really what I was looking for.
So I have created Dinoloop powered by Typescript (has interfaces, classes, abstract classes and strong oops). The package is pretty stable now.
With Dinoloop you can build enterprise level applications in a scalable architecture.
It uses Dependency Injection framework but you can configure any DI frameworks available in typescript. Dinoloop enables typescript to use as a Nodejs REST framework that helped me to maintain common typescript codebase for both angular and node projects.
So, Dinoloop is a perfect fit for typescript lovers and angular developers.
var mongoose = require('../DBSchema/SchemaMapper');
var UserSchema = mongoose.model('User');
var UserController = function(){
this.insert = (data) => {
return new Promise((resolve, reject) => {
var user = new UserSchema({
userName: data.userName,
password: data.password
});
user.save().then(() => {
resolve({status: 200, message: "Added new user"});
}).catch(err => {
reject({status: 500, message: "Error:- "+err});
})
})
}
this.update = (id, data) => {
return new Promise((resolve, reject) => {
UserSchema.update({_id: id}, data).then(() => {
resolve({status: 200, message: "update user"});
}).catch(err => {
reject({status: 500, message: "Error:- " + err});
})
})
}
this.searchAll = () => {
return new Promise((resolve, reject) => {
UserSchema.find().exec().then((data) => {
resolve({status: 200, data: data});
}).catch(err => {
reject({status: 500, message: "Error:- " + err});
})
})
}
this.search = (id) => {
return new Promise((resolve, reject) => {
UserSchema.find({_id:id}).exec().then(user => {
resolve({status: 200, data: user});
}).catch(err => {
reject({status: 500, message: "Error:- " + err});
})
})
}
this.delete = (id) => {
return new Promise((resolve, reject) => {
UserSchema.remove({_id:id}).then(() => {
resolve({status: 200, message: "remove user"});
}).catch(err => {
reject({status: 500, message:"Error:- " + err});
})
})
}
}
module.exports = new UserController();
///Route
var express = require('express');
var router = express.Router();
var Controller = require('./User.Controller');
router.post('/', (req, res) => {
Controller.insert(req.body).then(data => {
res.status(data.status).send({message: data.message});
}).catch(err => {
res.status(err.status).send({message: err.message});
})
});
router.put('/:id', (req, res) => {
Controller.update(req.params.id, req.body).then(data => {
res.status(data.status).send({message: data.message});
}).catch(err => {
res.status(err.status).send({message: err.message});
})
});
router.get('/', (req, res) => {
Controller.searchAll().then(data => {
res.status(data.status).send({data: data.data});
}).catch(err => {
res.status(err.status).send({message: err.message});
});
});
router.get('/:id', (req, res) => {
Controller.search(req.params.id).then(data => {
res.status(data.status).send({data: data.data});
}).catch(err => {
res.status(err.status).send({message: err.message});
});
});
router.delete('/:id', (req, res) => {
Controller.delete(req.params.id).then(data => {
res.status(data.status).send({message: data.message});
}).catch(err => {
res.status(err.status).send({message: err.message});
})
})
module.exports = router;
//db`enter code here`schema
var mongoose = require('mongoose');
const Schema = mongoose.Schema;
var Supplier =new Schema({
itemId:{
type:String,
required:true
},
brand:{
type:String,
required:true
},
pno:{
type:String,
required:true
},
email:{
type:String,
required:true
}
});
mongoose.model('Inventory',Inventory);
mongoose.model('Supplier',Supplier);
mongoose.connect('mongodb://127.0.0.1:27017/LAB', function (err) {
if (err) {
console.log(err);
process.exit(-1);
}
console.log("Connected to the db");
});
module.exports = mongoose;