How to use @loopback/rest - 10 common examples

To help you get started, we’ve selected a few @loopback/rest examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github strongloop / loopback-next / packages / authentication / src / __tests__ / fixtures / strategies / basic-strategy.ts View on Github external
extractCredentials(request: Request): BasicAuthenticationStrategyCredentials {
    if (!request.headers.authorization) {
      throw new HttpErrors.Unauthorized(`Authorization header not found.`);
    }

    // for example : Basic Z2l6bW9AZ21haWwuY29tOnBhc3N3b3Jk
    const authHeaderValue = request.headers.authorization;

    if (!authHeaderValue.startsWith('Basic')) {
      throw new HttpErrors.Unauthorized(
        `Authorization header is not of type 'Basic'.`,
      );
    }

    //split the string into 2 parts. We are interested in the base64 portion
    const parts = authHeaderValue.split(' ');
    if (parts.length !== 2)
      throw new HttpErrors.Unauthorized(
        `Authorization header value has too many parts. It must follow the pattern: 'Basic xxyyzz' where xxyyzz is a base64 string.`,
      );
    const encryptedCredentails = parts[1];

    // decrypt the credentials. Should look like :   'username:password'
    const decryptedCredentails = Buffer.from(
      encryptedCredentails,
      'base64',
github strongloop / loopback-next / packages / boot / src / __tests__ / fixtures / multiple.artifact.ts View on Github external
// Copyright IBM Corp. 2019. All Rights Reserved.
// Node module: @loopback/boot
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {get} from '@loopback/rest';

export class ArtifactOne {
  @get('/one')
  one() {
    return 'ControllerOne.one()';
  }
}

export class ArtifactTwo {
  @get('/two')
  two() {
    return 'ControllerTwo.two()';
  }
}

export function hello() {
  return 'hello world';
}
github IBM / blockchainbean2 / web-app / src / controllers / world-state.controller.ts View on Github external
console.log(result)
    //check if key does not exist, if so, send 404
    if ( result.indexOf( errorMessage ) > -1 ) {
      result = new Error(result);
    }
    return result 
  }

  /**
   * 
   * 

   * @param key 
   * @returns Request was successful
   */
  @operation('delete', '/worldstate/{key}')
  async deleteByKey(@param({ name: 'key', in: 'path' }) key: string): Promise {
    let networkObj = await blockchainClient.connectToNetwork();
    let result = await blockchainClient.deleteByKey(networkObj.contract, key);
    console.log(result)
    // var rez = JSON.parse(result.toString());
    console.log('before rez: ')
    console.log(result)
    //check if key does not exist, if so, send 404
    if ( result.indexOf( errorMessage ) > -1 ) {
      result = new Error(result);
    }
    return result 
  }

}
github strongloop / loopback-next / packages / example-codehub / src / controllers / user-controller.ts View on Github external
import {api, HttpErrors} from '@loopback/rest';

// Load OpenAPI specification for this controller
import {def} from './user-controller.api';

// Initially, bajtos was proposing
//   import {api} from '@loopback/controller-decorators';
// in order to allow 3rd party components to provide custom controllers
// while not depending on full loopback core
// After discussion with @ritch, we decided this is preliminary optimization
// that can be left for later

import {inject} from '@loopback/core';

// Notice that the controler is not required to extend any Controller base class
@api(def)
export class UserController {
  // Remote methods are returning a Promise and should be implemented as
  // async functions
  // This is required because most real world methods need to talk to
  // other services, which always takes more than a single tick of event loop
  //
  // This method can be called from other controllers/method the following way:
  //    const user: UserResponse =
  //      await userController.getUserByUsername('bajtos');
  //    console.log(user.email);
  public async getUserByUsername(username: string): Promise {
    return new UserResponse({name: username});
  }

  public async getAuthenticatedUser(
    @inject('userId') userId: number,
github strongloop / loopback4-example-shopping / packages / shopping / src / services / jwt-service.ts View on Github external
async generateToken(userProfile: UserProfile): Promise {
    if (!userProfile) {
      throw new HttpErrors.Unauthorized(
        'Error generating token : userProfile is null',
      );
    }
    const userInfoForToken = {
      id: userProfile[securityId],
      name: userProfile.name,
      email: userProfile.email,
    };
    // Generate a JSON Web Token
    let token: string;
    try {
      token = await signAsync(userInfoForToken, this.jwtSecret, {
        expiresIn: Number(this.jwtExpiresIn),
      });
    } catch (error) {
      throw new HttpErrors.Unauthorized(`Error encoding token : ${error}`);
github sourcefuse / loopback4-starter / src / modules / auth / login.controller.ts View on Github external
} else if (payload.userId) {
        user = await this.userRepo.findById(payload.userId);
      }
      if (!user) {
        throw new HttpErrors.Unauthorized(
          AuthenticateErrorKeys.UserDoesNotExist,
        );
      }
      const userTenant = await this.userTenantRepo.findOne({
        where: {
          userId: user.getId(),
          tenantId: user.defaultTenant,
        },
      });
      if (!userTenant) {
        throw new HttpErrors.Unauthorized(
          AuthenticateErrorKeys.UserDoesNotExist,
        );
      } else if (userTenant.status !== 'active') {
        throw new HttpErrors.Unauthorized(AuthenticateErrorKeys.UserInactive);
      }
      // Create user DTO for payload to JWT
      const authUser: AuthUser = new AuthUser(user);
      authUser.tenant = await this.userTenantRepo.tenant(userTenant.id);
      const role = await this.userTenantRepo.role(userTenant.id);
      const utPerms = await this.utPermsRepo.find({
        where: {
          userTenantId: userTenant.id,
        },
        fields: {
          permission: true,
          allowed: true,
github dofapi / dofapi / server / src / controllers / set-equipments.controller.ts View on Github external
requestBody,
} from '@loopback/rest';
import { Equipment } from '../models';


export class SetEquipmentsController {
  constructor(
    @repository(SetRepository) protected setRepo: SetRepository,
  ) { }

  // @post('/sets/{id}/equipments')
  // async create(@param.path.number('id') id: number, @requestBody() equipment: Equipment) {
  //   return await this.setRepo.equipments(id).create(equipment);
  // }

  @get('/set/{id}/equipments', {
    responses: {
      '200': {
        description: "Array of equipment's belonging to set",
        content: {
          'application/json': {
            schema: { type: 'array', items: { 'x-ts-type': Equipment } },
          },
        },
      },
    },
  })
  async find(
    @param.path.number('id') id: number,
    @param.query.object('filter') filter?: Filter,
  ): Promise {
    return await this.setRepo.equipments(id).find(filter);
github strongloop / loopback4-example-shopping / packages / shopping / src / controllers / ping.controller.ts View on Github external
additionalProperties: false,
          },
        },
      },
    },
  },
};

/**
 * A simple controller to bounce back http requests
 */
export class PingController {
  constructor(@inject(RestBindings.Http.REQUEST) private req: Request) {}

  // Map to `GET /ping`
  @get('/ping', {
    responses: {
      '200': PING_RESPONSE,
    },
  })
  ping(): object {
    // Reply with a greeting, the current time, the url, and request headers
    return {
      greeting: 'Hello from LoopBack',
      date: new Date(),
      url: this.req.url,
      headers: Object.assign({}, this.req.headers),
    };
  }
}
github strongloop / loopback-next / packages / v3compat / src / remoting / rest-adapter.ts View on Github external
...args: OperationArgs
    ) {
      if (!sharedMethod.isStatic) {
        // TODO: invoke sharedCtor to obtain the model instance
        throw new HttpErrors.NotImplemented(
          'Instance-level shared methods are not supported yet.',
        );
      }

      return this.invokeStaticMethod(sharedMethod, args);
    };

    debug('    %s %s %j', verb, path, spec);

    // Define OpenAPI Spec Operation for the shared method
    operation(
      convertVerb(verb),
      joinUrlPaths(this.restApiRoot, convertPathFragments(path)),
      spec,
    )(controllerClass.prototype, key, {});
  }
}
github strongloop / loopback-next / packages / rest-crud / src / crud-rest.controller.ts View on Github external
filter?: Filter,
    ): Promise {
      return this.repository.findById(id, filter);
    }

    @get('/count', {
      ...response(200, `${modelName} count`, {schema: CountSchema}),
    })
    async count(
      @param.query.object('where', getWhereSchemaFor(modelCtor))
      where?: Where,
    ): Promise {
      return this.repository.count(where);
    }

    @patch('/', {
      ...response(200, `Count of ${modelName} models updated`, {
        schema: CountSchema,
      }),
    })
    async updateAll(
      @body(modelCtor, {partial: true}) data: Partial,
      @param.query.object('where', getWhereSchemaFor(modelCtor))
      where?: Where,
    ): Promise {
      return this.repository.updateAll(
        // FIXME(bajtos) Improve repository API to support this use case
        // with no explicit type-casts required
        data as DataObject,
        where,
      );
    }