-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmongomicrosrv.js
More file actions
74 lines (65 loc) · 2.73 KB
/
mongomicrosrv.js
File metadata and controls
74 lines (65 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
'use strict'
const dotEnvRes = require('dotenv').config({ path: './variables.env' });
if (dotEnvRes.error) {
throw dotEnvRes.error
}
console.log(dotEnvRes.parsed)
const connectToDatabase = require('./db');
const User = require('./models/user');
const Post = require('./models/post');
module.exports.mongoms = async (event, context) => {
context.callbackWaitsForEmptyEventLoop = false;
function httpResp(status, data){
return {
statusCode: status,
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': 'GET, PUT, POST, OPTIONS, DELETE, HEAD',
"Access-Control-Allow-Credentials" : true,
'Version':'17.10.15.4'
}
}
}
async function dbOperation(entity, opr, ...params) {
try{
let resp = await entity[opr](...params);
return httpResp(200, resp);
}
catch(err) {
console.dir(err);
return httpResp(500, err);
}
}
await connectToDatabase();
if (['GET','POST','DELETE','PUT'].indexOf(event.httpMethod) === -1 ) return httpResp(422, `HttpMethod ${event.httpMethod} is not implemented`);
if (event.pathParameters === undefined || event.pathParameters.entity === undefined) return httpResp(422, 'Path parameter entity not found');
var entity;
try{
entity = eval(event.pathParameters.entity);
if (typeof entity !== 'function') return httpResp(422, `Mongoose entity ${event.pathParameters.entity} is not found`);
}
catch(err){
return httpResp(422, `Mongoose entity ${event.pathParameters.entity} is not found`);
}
console.dir(event);
switch (event.httpMethod) {
case 'GET':
if (event.pathParameters.id)
return await dbOperation(entity, 'findById', event.pathParameters.id);
else if (event.pathParameters.filter)
return await dbOperation(entity, 'find', JSON.parse(decodeURI(event.pathParameters.filter)));
else
return httpResp(422, 'GET request should have id or filter');
case 'POST':
return await dbOperation(entity, 'findOneAndUpdate', {'_id': event.pathParameters.id}, {$set: JSON.parse(event.body)}, {new: true});
case 'PUT':
console.dir(event.body);
return await dbOperation(entity, 'create', JSON.parse(event.body));
case 'DELETE':
return await dbOperation(entity, 'deleteOne', {'_id': event.pathParameters.id});
}
return httpResp(422, "Code needs improvement");
};