How to use the @phenyl/utils.createServerError function in @phenyl/utils

To help you get started, we’ve selected a few @phenyl/utils 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 phenyl / phenyl / modules / http-rules / src / server-logic.ts View on Github external
async handleApiRequest(encodedHttpRequest: EncodedHttpRequest) {
    let responseData: GeneralResponseData;
    // This line casts restApiHandler to supertype so that it should receive pre-sanitized data.
    const restApiHandler: GeneralRestApiHandler = this.restApiHandler;

    try {
      // 1. Decoding Request
      const requestData = decodeRequest(encodedHttpRequest);

      // 2. Invoking PhenylRestApi
      responseData = await restApiHandler.handleRequestData(requestData);
    } catch (err) {
      responseData = {
        type: "error",
        payload: createServerError(err)
      };
    }

    // 3. Encoding Response
    return encodeResponse(responseData);
  }
github phenyl / phenyl / modules / rest-api / src / phenyl-rest-api.ts View on Github external
>(
    reqData: RequestDataWithTypeMapForResponse
  ): Promise | ErrorResponseData> {
    // TODO: use HandlerRequest Type instead of Promise
    try {
      assertValidRequestData(reqData);
      const session = await this.sessionClient.get(reqData.sessionId!);
      const executor = this.getExecutor(
        reqData.method,
        this.extractName(reqData)
      );
      const isAccessible = await executor.authorize(reqData, session);
      if (!isAccessible) {
        return {
          type: "error",
          payload: createServerError("Authorization Required.", "Unauthorized")
        };
      }
      const normalizedReqData = await executor.normalize(reqData, session);

      try {
        await executor.validate(normalizedReqData, session);
      } catch (validationError) {
        validationError.message = `Validation Failed. ${
          validationError.mesage
        }`;
        return {
          type: "error",
          payload: createServerError(validationError, "BadRequest")
        };
      }
github phenyl / phenyl / modules / mongodb / src / mongodb-client.ts View on Github external
async getByIds>(
    query: IdsQuery
  ): Promise>> {
    const { entityName, ids } = query;
    const coll = this.conn.collection(entityName);
    // $FlowIssue(find-operation)
    const result = await coll.find({ _id: { $in: ids.map(ObjectID) } });
    if (result.length === 0) {
      throw createServerError(
        '"PhenylMongodbClient#getByIds()" failed. Could not find any entity with the given query.',
        "NotFound"
      );
    }
    // @ts-ignore @TODO: improve the types in MongoDbCollection
    return result.map(filterOutputEntity);
  }
github phenyl / phenyl / modules / memory-db / src / phenyl-memory-db-client.ts View on Github external
throw createServerError(
          `Entity has been locked. entityName:${entityName}, id: ${id}`
        );
      }
      const operation = PhenylStateUpdater.updateById(
        this.entityState,
        command
      );
      // @ts-ignore operation is nonbreaking
      this.entityState = update(this.entityState, operation);
      return PhenylStateFinder.get(this.entityState, {
        entityName,
        id
      });
    } catch (error) {
      throw createServerError(
        '"PhenylMemoryClient#updateAndGet()" failed. Could not find any entity with the given query.',
        "NotFound"
      );
    }
  }
  /**
github phenyl / phenyl / modules / rest-api / src / definition-executor.ts View on Github external
async execute(
    reqData: GeneralUserEntityRequestData,
    session?: Session
  ): Promise {
    // TODO: use HandlerRequest Type instead of Promise
    if (reqData.method == "logout") {
      return this.logout(reqData.payload);
    }
    if (reqData.method == "login") {
      return this.login(reqData.payload, session);
    }

    if (session === undefined) {
      const errorResult: ErrorResponseData = {
        type: "error",
        payload: createServerError(
          `Method ${reqData.method} requires an active session`,
          "Unauthorized"
        )
      };
      return errorResult;
    }
    return this.definition.wrapExecution!(
      reqData,
      session,
      executeEntityRequestData.bind(this, this.client)
    );
  }
github phenyl / phenyl / modules / memory-db / src / phenyl-memory-db-client.ts View on Github external
async updateAndGet>(
    command: IdUpdateCommand
  ): Promise {
    const { entityName, id, filter } = command;
    try {
      const entity = PhenylStateFinder.get(this.entityState, {
        entityName,
        id
      });
      const matched = filter ? retrieve([entity], filter).length === 1 : true;

      if (!matched) {
        throw createServerError(
          `Entity has been locked. entityName:${entityName}, id: ${id}`
        );
      }
      const operation = PhenylStateUpdater.updateById(
        this.entityState,
        command
      );
      // @ts-ignore operation is nonbreaking
      this.entityState = update(this.entityState, operation);
      return PhenylStateFinder.get(this.entityState, {
        entityName,
        id
      });
    } catch (error) {
      throw createServerError(
        '"PhenylMemoryClient#updateAndGet()" failed. Could not find any entity with the given query.',
github phenyl / phenyl / modules / standards / src / standard-user-definition.ts View on Github external
const result = await this.entityClient.findOne({
        entityName,
        where: {
          [accountPropName]: account,
          [passwordPropName]: this.encrypt(password)
        }
      });
      const user = removePasswordFromResponseEntity(
        result.entity,
        passwordPropName
      );
      const expiredAt = new Date(Date.now() + ttl * 1000).toISOString();
      const preSession = { expiredAt, entityName, userId: user.id };
      return { preSession, user, versionId: result.versionId };
    } catch (e) {
      throw createServerError(e.message, "Unauthorized");
    }
  }
github phenyl / phenyl / modules / rest-api / src / definition-executor.ts View on Github external
async execute(
    reqData: GeneralEntityRequestData,
    session?: Session
  ): Promise {
    if (session === undefined) {
      const errorResult: ErrorResponseData = {
        type: "error",
        payload: createServerError(
          `Execute method ${reqData.method} must needs session`
        )
      };
      return errorResult;
    }
    return this.definition.wrapExecution!(
      reqData,
      session,
      executeEntityRequestData.bind(this, this.client)
    );
  }
}
github phenyl / phenyl / modules / rest-api / src / phenyl-rest-api.ts View on Github external
name: string
  ): DefinitionExecutor {
    if (methodName === "login" || methodName === "logout") {
      if (this.definitionExecutors.user[name]) {
        return this.definitionExecutors.user[name];
      }
      throw createServerError(
        `No user entity name found: "${name}"`,
        "NotFound"
      );
    }
    if (methodName === "runCustomQuery") {
      if (this.definitionExecutors.customQuery[name]) {
        return this.definitionExecutors.customQuery[name];
      }
      throw createServerError(
        `No user custom query name found: "${name}"`,
        "NotFound"
      );
    }
    if (methodName === "runCustomCommand") {
      if (this.definitionExecutors.customCommand[name]) {
        return this.definitionExecutors.customCommand[name];
      }
      throw createServerError(
        `No user custom command name found: "${name}"`,
        "NotFound"
      );
    }

    if (this.definitionExecutors.entity[name]) {
      return this.definitionExecutors.entity[name];