Meg*_*Dev 2 javascript api rest meteor
首先,我是Web框架的新手.我们正在使用Meteor.我有一个学生收藏:
Students = new Mongo.Collection('students');
Run Code Online (Sandbox Code Playgroud)
目前,我们将Rest API定义为:
// Maps to: /api/getAllStudents
Restivus.addRoute('getAllStudents', {authRequired: false}, {
get: function () {
var students = Students.find().fetch();
if (students.length > 0) {
return {status: 'success',count:students.length,data: students};
}
else {
return {
statusCode: 404,
body: {status: 'fail', message: 'Students not found'}
};
}}
});
};
Run Code Online (Sandbox Code Playgroud)
现在,可以有另一个API getStudentByName
// Maps to: /api/getStudentByName by name
Restivus.addRoute('getStudentByName', {authRequired: false}, {
get: function () {
var obj = {};
for(var key in this.queryParams){
var val = this.queryParams[key];
obj[key] = val;
}
var students = Students.find(obj).fetch();
if (student.length > 0) {
return {status: 'success',count: students.length, data: students};
}
return {
statusCode: 404,
body: {status: 'fail', message: 'Students not found'}
};
}
});
Run Code Online (Sandbox Code Playgroud)
目前我正在访问它们
http://localhost:3000/api/getAllStudents
Run Code Online (Sandbox Code Playgroud)
和
http://localhost:3000/api/getStudentByName?name='abc'
Run Code Online (Sandbox Code Playgroud)
我将为学生提供更多此类API(获取,放置,发布,删除).此外,我还有更多资源,如教师,课程等.每个资源都会定义一组API.现在,我想以更整洁的方式设计我的API(我知道这是非常模糊和无组织的).我想最终称他们为
http://localhost:3000/api/Students/getAllStudents http://localhost:3000/api/Students/getStudentByName?name='abc'
现在,我有一个Student-api.js,我已经放置了这两个API和classes-api.js以及包含各自API的classes-api.js.但是,这太过于非结构化了.可以使用像命名空间一样的"东西"吗?任何帮助真的很受欢迎..
REST API不应包含动词.动词由HTTP提供.
// All Students
GET http://localhost:3000/api/students
Run Code Online (Sandbox Code Playgroud)
一种可能的方法是提供过滤器参数
// Students named Mark
GET http://localhost:3000/api/students?filter=name%3DMark
// Teachers whose last name is Johnson
GET http://localhost:3000/api/students?filter=lastName%3DJohnson
Run Code Online (Sandbox Code Playgroud)
这是使用统一接口的REST API的美妙之处.现在,您的所有API调用都可以支持相同的过滤器参数.
以下是在单个字段上进行相等匹配的简单示例,可能需要进行调整,因为我还没有测试过.您可以通过支持多个字段和不同的运算符来改进它以使过滤更加智能化.
var filterableCollections = ['students', 'teachers'];
filterableCollections.forEach(function(collectionName) {
var Collection = new Mongo.Collection(collectionName);
Restivus.addRoute(collectionName, {authRequired: false}, {
get: function() {
var items;
var filter = this.queryParams.filter;
if (filter) {
var fieldNameValue = filter.split('=');
var queryObj = {};
queryObj[fieldNameValue[0]] = fieldNameValue[1];
items = Collection.find(queryObj).fetch();
} else {
items = Collection.find().fetch();
}
var response;
if (items.length > 0) {
response = {status: 'success', count: items.length, data: items};
} else {
response = {
statusCode: 404,
body: {status: 'fail', message: collectionName + ' not found'}
};
}
return response;
}
});
});
Run Code Online (Sandbox Code Playgroud)
注意:%3D是URL的编码=
| 归档时间: |
|
| 查看次数: |
138 次 |
| 最近记录: |