node-odata icon indicating copy to clipboard operation
node-odata copied to clipboard

A better way to declare a resource.

Open zackyang000 opened this issue 8 years ago • 3 comments

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;
  }
}

zackyang000 avatar Jun 01 '17 00:06 zackyang000

Hi @TossShinHwa, thanks for informing!

Here are the features, that current version doesn't has, and which I have to implement bypassing node-odata:

  1. Case insensitive search in many fields at once. Similar to this: $filter=substringof('foo',article) eq true or substringof('foo',mail) eq true
  2. Async calls inside .post.before() or so. I need to perform different async mongo calls while processing the requests. It will be great to have possibility to do return next() inside before()

pavelseverov avatar Jun 01 '17 08:06 pavelseverov

Hi @pavelseverov correct, this 2 features I will add to next version, thanks for feedback.

zackyang000 avatar Jun 01 '17 11:06 zackyang000

Hello Zack,

I like it. This also defines the structure of a project. You have to know a little more here, but you also have more features.

r1mar avatar Sep 01 '22 06:09 r1mar