-
Notifications
You must be signed in to change notification settings - Fork 17
/
Service.js
111 lines (89 loc) · 2.71 KB
/
Service.js
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
'use strict';
const mongoose = require( 'mongoose' );
const autoBind = require( 'auto-bind' );
const { HttpResponse } = require( '../helpers/HttpResponse' );
class Service {
/**
* Base Service Layer
* @author Sunil Kumar Samanta
* @param model
*/
constructor( model ) {
this.model = model;
autoBind( this );
}
async getAll( query ) {
let { skip, limit, sortBy } = query;
skip = skip ? Number( skip ) : 0;
limit = limit ? Number( limit ) : 10;
sortBy = sortBy ? sortBy : { 'createdAt': -1 };
delete query.skip;
delete query.limit;
delete query.sortBy;
if ( query._id ) {
try {
query._id = new mongoose.mongo.ObjectId( query._id );
} catch ( error ) {
throw new Error( 'Not able to generate mongoose id with content' );
}
}
try {
const items = await this.model
.find( query )
.sort( sortBy )
.skip( skip )
.limit( limit ),
total = await this.model.countDocuments( query );
return new HttpResponse( items, { 'totalCount': total } );
} catch ( errors ) {
throw errors;
}
}
async get( id ) {
try {
const item = await this.model.findById( id );
if ( !item ) {
const error = new Error( 'Item not found' );
error.statusCode = 404;
throw error;
}
return new HttpResponse( item );
} catch ( errors ) {
throw errors;
}
}
async insert( data ) {
try {
const item = await this.model.create( data );
if ( item ) {
return new HttpResponse( item );
}
throw new Error( 'Something wrong happened' );
} catch ( error ) {
throw error;
}
}
async update( id, data ) {
try {
const item = await this.model.findByIdAndUpdate( id, data, { 'new': true } );
return new HttpResponse( item );
} catch ( errors ) {
throw errors;
}
}
async delete( id ) {
try {
const item = await this.model.findByIdAndDelete( id );
if ( !item ) {
const error = new Error( 'Item not found' );
error.statusCode = 404;
throw error;
} else {
return new HttpResponse( item, { 'deleted': true } );
}
} catch ( errors ) {
throw errors;
}
}
}
module.exports = { Service };