Important:Before running this generator, you must create an application using the application generator.Then you must run the command from the root directory of the application.

Synopsis

Adds a new empty controller to a LoopBack application.

  1. lb4 controller [options] [<name>]

Options

—controllerType : Type of the controller.

Valid types are BASIC and REST. BASIC corresponds to an empty controller,whereas REST corresponds to REST controller with CRUD methods.Standard options

  • -h, —help
  • Print the generator’s options and usage.
  • —skip-cache
  • Do not remember prompt answers. Default is false.
  • —skip-install
  • Do not automatically install dependencies. Default is false.
  • -c, —config
  • JSON file name or value to configure options
  • —format
  • Format generated code using npm run lint:fixFor example,
  1. lb4 app --config config.json
  2. lb4 app --config '{"name":"my-app"}'
  3. cat config.json | lb4 app --config stdin
  4. lb4 app --config stdin < config.json
  5. lb4 app --config stdin << EOF
  6. > {"name":"my-app"}
  7. > EOF
  • -y, —yes
  • Skip all confirmation prompts with default or provided value

Arguments

<name> - Optional name of the controller to create as an argument to thecommand. If provided, the tool will use that as the default when it prompts forthe name.

Interactive Prompts

The tool will prompt you for:

  • Name of the controller. If the name had been supplied from the commandline, the prompt is skipped and the controller is built with the name from thecommand-line argument.
  • Type of the controller. You can select from the following types:
    • Empty Controller - An empty controller definition
    • REST Controller with CRUD Methods - A controller wired up to a model andrepository definition, with pre-defined CRUD methods.

Empty Controller

If you select the Empty Controller, it will generate a nearly-empty templatebased on the given name:

  1. // Uncomment these imports to begin using these cool features!
  2. // import {inject} from '@loopback/context';
  3. export class FooController {
  4. constructor() {}
  5. }

REST Controller with CRUD Methods

If you select the REST Controller with CRUD Methods type, you will then be askedto select:

  • The model to use for the CRUD function definitions
  • The repository for this model that provides datasource connectivity
  • The REST path name to host the endpoints onThe prompts that list out the models and repositories to choose from to buildthe controller with are chosen from the existing model/repository files on disc.From the LoopBack 4 project that the CLI is run in, the CLI tool will search forthe following files in the LoopBack 4 project it runs in:

  • src/repositories/*.repository.ts

  • src/repositories/*.repository.js
  • src/models/*.model.ts
  • src/models/*.model.jsFiles that match these patterns will then be identified based on the stringbefore the first . separator. For example, file models/product.model.ts isidentified as a source of Product model.

Note:

Please note that the model and repository typing information will be based onhow the model/repository files are named; the CLI tooling does not read theactual artifact class names inside the files.

Warning: If you do not have a model and repository to select,then you will receive an error!

Here’s an example of what the template will produce given a Todo model and aTodoRepository:

  1. import {
  2. Count,
  3. CountSchema,
  4. Filter,
  5. repository,
  6. Where
  7. } from '@loopback/repository';
  8. import {
  9. post,
  10. param,
  11. get,
  12. getFilterSchemaFor,
  13. getModelSchemaRef,
  14. getWhereSchemaFor,
  15. patch,
  16. del,
  17. requestBody,
  18. } from '@loopback/rest';
  19. import {Todo} from '../models';
  20. import {TodoRepository} from '../repositories';
  21. export class TodoController {
  22. constructor(
  23. @repository(TodoRepository) public todoRepository: TodoRepository,
  24. ) {}
  25. @post('/todos', {
  26. responses: {
  27. '200': {
  28. description: 'Todo model instance',
  29. content: {'application/json': {schema: getModelSchemaRef(Todo)}},
  30. },
  31. },
  32. })
  33. async create(
  34. @requestBody({
  35. content: {
  36. 'application/json': {
  37. schema: getModelSchemaRef(Todo, {exclude: ['id']}),
  38. },
  39. },
  40. })
  41. todo: Omit<Todo, 'id'>,
  42. ): Promise<Todo> {
  43. return this.todoRepository.create(todo);
  44. }
  45. @get('/todos/count', {
  46. responses: {
  47. '200': {
  48. description: 'Todo model count',
  49. content: {'application/json': {schema: CountSchema}},
  50. },
  51. },
  52. })
  53. async count(
  54. @param.query.object('where', getWhereSchemaFor(Todo)) where?: Where<Todo>,
  55. ): Promise<Count> {
  56. return this.todoRepository.count(where);
  57. }
  58. @get('/todos', {
  59. responses: {
  60. '200': {
  61. description: 'Array of Todo model instances',
  62. content: {
  63. 'application/json': {
  64. schema: {type: 'array', items: getModelSchemaRef(Todo)},
  65. },
  66. },
  67. },
  68. },
  69. })
  70. async find(
  71. @param.query.object('filter', getFilterSchemaFor(Todo))
  72. filter?: Filter<Todo>,
  73. ): Promise<Todo[]> {
  74. return this.todoRepository.find(filter);
  75. }
  76. @patch('/todos', {
  77. responses: {
  78. '200': {
  79. description: 'Todo PATCH success count',
  80. content: {'application/json': {schema: CountSchema}},
  81. },
  82. },
  83. })
  84. async updateAll(
  85. @requestBody({
  86. content: {
  87. 'application/json': {
  88. schema: getModelSchemaRef(Todo, {partial: true}),
  89. },
  90. },
  91. })
  92. todo: Partial<Todo>
  93. @param.query.object('where', getWhereSchemaFor(Todo)) where?: Where<Todo>,
  94. ): Promise<Count> {
  95. return this.todoRepository.updateAll(todo, where);
  96. }
  97. @get('/todos/{id}', {
  98. responses: {
  99. '200': {
  100. description: 'Todo model instance',
  101. content: {'application/json': {schema: getModelSchemaRef(Todo)}},
  102. },
  103. },
  104. })
  105. async findById(@param.path.number('id') id: number): Promise<Todo> {
  106. return this.todoRepository.findById(id);
  107. }
  108. @patch('/todos/{id}', {
  109. responses: {
  110. '204': {
  111. description: 'Todo PATCH success',
  112. },
  113. },
  114. })
  115. async updateById(
  116. @param.path.number('id') id: number,
  117. @requestBody({
  118. content: {
  119. 'application/json': {
  120. schema: getModelSchemaRef(Todo, {partial: true}),
  121. },
  122. },
  123. })
  124. todo: Partial<Todo>,
  125. ): Promise<void> {
  126. await this.todoRepository.updateById(id, todo);
  127. }
  128. @del('/todos/{id}', {
  129. responses: {
  130. '204': {
  131. description: 'Todo DELETE success',
  132. },
  133. },
  134. })
  135. async deleteById(@param.path.number('id') id: number): Promise<void> {
  136. await this.todoRepository.deleteById(id);
  137. }
  138. }