Skip to content

Commit

Permalink
fix: send 404 for findById(), if resource is not found
Browse files Browse the repository at this point in the history
send 404 for findById(), if resource is not found
  • Loading branch information
Hage Yaapa committed Aug 28, 2018
1 parent a408377 commit 8c5cf03
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
15 changes: 13 additions & 2 deletions examples/todo/src/controllers/todo.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,16 @@

import {inject} from '@loopback/core';
import {repository} from '@loopback/repository';
import {del, get, param, patch, post, put, requestBody} from '@loopback/rest';
import {
del,
get,
param,
patch,
post,
put,
requestBody,
throwNotFoundErrorWhenNull,
} from '@loopback/rest';
import {Todo} from '../models';
import {TodoRepository} from '../repositories';
import {GeocoderService} from '../services';
Expand Down Expand Up @@ -35,7 +44,9 @@ export class TodoController {
@param.path.number('id') id: number,
@param.query.boolean('items') items?: boolean,
): Promise<Todo> {
return await this.todoRepo.findById(id);
const result = await this.todoRepo.findById(id);
throwNotFoundErrorWhenNull(result);
return result;
}

@get('/todos')
Expand Down
1 change: 1 addition & 0 deletions packages/rest/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export * from './rest.component';
export * from './rest.server';
export * from './sequence';
export * from './rest-http-error';
export * from './utils';

// export all errors from external http-errors package
import * as HttpErrors from 'http-errors';
Expand Down
16 changes: 16 additions & 0 deletions packages/rest/src/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import * as HttpErrors from 'http-errors';

export function throwNotFoundErrorWhenNull(model: null): never;
export function throwNotFoundErrorWhenNull<T>(model: T): void;

export function throwNotFoundErrorWhenNull<T>(model: T | null): T {
if (model) return model;
// WIP: don't mind these temporary hard-coded values
const modelName = '';
const id = 2;
const msg = `Unknown "${modelName}" id "${id}".`;
const error = new HttpErrors.HttpError(msg);
error.statusCode = error.status = 404;
error.code = 'MODEL_NOT_FOUND';
throw error;
}

0 comments on commit 8c5cf03

Please sign in to comment.