We want to make some changes in the next version. Defining a resource in the following way should be clearer. If you have any suggestions, please comment on this issue.
import { Resource, queryable, action } from 'node-odata';
import createError from 'http-errors';
const bookInfo = {
title: String,
price: Number,
};
function async checkUserAuth(req) {
// Check the permissions of the user role
const user = await User.get(req.query.id);
if (user.role === 'guest') return false;
}
// Resource contains five query methods: `list/get/create/update/remove`, you can selectively cover it as needed
// In addition, you can also declare the action to do some special operations, Use `@action` decorator
export default class Book extends Resource {
constructor() {
super('book', bookInfo);
}
// `queryable` is used to make some restrictions on the list request,
// such as default pageSize / maxTop / allowed orderby field.
@queryable({ pageSize: 10, maxTop: 50 })
async list(next) {
// You can manually call the query method `next()`, so you can do something before or after of the query.
await next();
}
async get(next) {
// Check if resource meets the requirements
const entity = req.body;
if (entity.title === undefined) {
throw createError.UnprocessableEntity({...});
}
const entity = await next();
}
// If you do not need to do anything, you can not declare the method
// async create(next) {
// next();
// }
@checkUserAuth
async remove(next) {
next();
}
@checkUserAuth
async update(next) {
next();
}
@action['/50off']
@checkUserAuth
async halfPriceAction(id, query) {
const entity = await Book.findOneById(id);
entity.price /= 2;
await entity.save();
return entity;
}
}
We want to make some changes in the next version. Defining a resource in the following way should be clearer. If you have any suggestions, please comment on this issue.