Bladeren bron

started route generator for server side.

Tomislav Cvetic 8 jaren geleden
bovenliggende
commit
e1d73f312a
3 gewijzigde bestanden met toevoegingen van 189 en 4 verwijderingen
  1. 5 3
      server/basicSchema.js
  2. 3 1
      server/project/route.js
  3. 181 0
      server/routeGen.js

+ 5 - 3
server/basicSchema.js

@@ -7,16 +7,18 @@
   * copy current version
   *
 */
-import { Schema } from 'mongoose'
+import { Schema, model } from 'mongoose'
 
 const historySchema = new Schema({
   author: [Schema.Types.ObjectId],
   created: Date,
-  version: Number,
   tag: String,
-  reference: [Schema.Types.ObjectId]
+  reference: [Schema.Types.ObjectId],
+  head: Boolean
 })
 
+export const History = model('History', historySchema)
+
 const basicSchema = {
   name: {
     type: String,

+ 3 - 1
server/project/route.js

@@ -4,9 +4,11 @@ import mongoose from 'mongoose'
 const routing = {
   /** GET handler (request one or more projects) */
   get: (req, res, next) => {
+    console.log(req.params)
+    console.log(req.query)
+    console.log(Project.schema.obj)
     const path = req.params['0']
     let id = req.params['1']
-    console.log(req.params)
     /** If the path doesn't match, call the next router */
     if (path !== '/project') {
       next()

+ 181 - 0
server/routeGen.js

@@ -0,0 +1,181 @@
+import mongoose from 'mongoose'
+import { History } from './basicSchema'
+
+function routeGen (model) {
+
+  /** GET handler (request one item or a list of items) */
+  function get (req, res, next) {
+    const path = req.params['0']
+    /** If the path doesn't match, call the next router */
+    if (path !== model.modelName.toLowerCase()) {
+      next()
+    }
+
+    let id = req.params['1']
+    /** check whether an id was specified. */
+    if (typeof id === 'string' && id.length > 1) {
+      // remove leading slash
+      id = id.substring(1)
+      try {
+        // try to convert the id string to a valid ObjectId
+        id = mongoose.Types.ObjectId(req.params['1'].substring(1))
+      } catch (err) {
+        // If id couldn't be converted, return an error message.
+        res.status(422)
+        res.send({error: err.message})
+        return
+      }
+      // if yes, return the one item
+      model.findOne({ _id: id }, function (err, item) {
+        if (err) {
+          res.status(404)
+          res.send(err)
+          return
+        }
+        res.json(item)
+      })
+    } else {
+      // if not, return a list of items
+      // limit the number of returned items and use an offset
+      const limit = req.query.limit ? Math.min(Math.max(parseInt(req.query.limit), 1), 100) : 20
+      const offset = req.query.offset ? Math.min(Math.max(parseInt(req.query.offset), 1), 100) : 20
+      model.find({}, {limit: limit, skip: offset}, function (err, items) {
+        if (err) {
+          res.status(404)
+          res.send(err)
+          return
+        }
+        res.json(items)
+      })
+    }
+  }
+
+  /** POST handler (insert a new item into the database) */
+  function post (req, res, next) {
+    const path = req.params['0']
+    // If the path doesn't match, call the next router
+    if (path !== model.modelName.toLowerCase()) {
+      next()
+    }
+
+    // create the new item
+    const item = new model(req.body)
+
+    // Check, if the model supports revision control
+    if (typeof model.schema.obj.__history !== 'undefined') {
+
+      item.__history = new History({
+        author: '',
+        created: Date(),
+        tag: '',
+        reference: [],
+        head: true
+      })
+    }
+
+    // save the item
+    item.save(function (err) {
+      if (err) {
+        res.status(422)
+        res.send(err)
+        return
+      }
+      res.send({ success: `${model.modelName} added.` })
+    })
+  }
+
+  /** PUT handler (update existing project) */
+  function put (req, res, next) {
+    const path = req.params['0']
+    /** If the path doesn't match, call the next router */
+    if (path !== model.modelName.toLowerCase()) {
+      next()
+    }
+
+    let id = req.params['1']
+    /** check whether an id was specified. */
+    if (typeof id === 'string' && id.length > 1) {
+      // remove leading slash
+      id = id.substring(1)
+      try {
+        // try to convert the id string to a valid ObjectId
+        id = mongoose.Types.ObjectId(req.params['1'].substring(1))
+      } catch (err) {
+        // If id couldn't be converted, return an error message.
+        res.status(422)
+        res.send({error: err.message})
+        return
+      }
+    }
+
+    // Find the object in the database
+    model.findOne({ _id: id }, function (err, item) {
+      if (err) {
+        res.status(404)
+        res.send(err)
+      }
+
+      // Check, if the model supports revision control
+      if (typeof model.schema.obj.__history !== 'undefined') {
+        // If yes, don't update the item, but create a new one based on the original
+        const newItem = model(item)
+        // replace the requested elements
+        for (let prop in req.body) {
+          newItem[prop] = req.body[prop]
+        }
+        // give it a new history with updated reference array. Set the head-indicator to true
+        newItem.__history = new History({
+          author: '',
+          created: Date(),
+          tag: '',
+          reference: [ ...item.__history.reference, item._id ],
+          head: true
+        })
+        // set the original item's head indicator to false
+        item.__history.head = false
+        // save the documents
+        newItem.save(function (err) {
+        if (err) {
+          res.status(422)
+          res.send(err)
+        }
+        res.json({ message: `${model.modelName} updated.` })
+      })
+      } else {
+        for (let prop in req.body) {
+          item[prop] = req.body[prop]
+        }
+      }
+
+      item.save(function (err) {
+        if (err) {
+          res.status(422)
+          res.send(err)
+        }
+        res.json({ message: `${model.modelName} updated.` })
+      })
+    })
+  },
+
+  /** DELETE handler (delete project) */
+  delete: (req, res, next) => {
+    const path = req.params['0']
+    const id = mongoose.Types.ObjectId(req.params['1'].substring(1))
+    /** If the path doesn't match, call the next router */
+    if (path !== '/project') {
+      next()
+    }
+
+    Project.remove({ _id: id }, function (err, project) {
+      if (err) {
+        res.send(err)
+      }
+      res.json({ message: 'Movie deleted.' })
+    })
+  }
+}
+
+export default routing
+
+
+export default routeGen