How to use the attempt function from joi

Find comprehensive JavaScript joi.attempt code examples handpicked from public code repositorys.

joi.attempt is a method in the joi validation library that attempts to validate a value against a schema, throwing an error if the validation fails.

6
7
8
9
10
11
12
13
14
15
const ClientCredentialsGrantType = require('./lib/client-credentials-grant-type');
const { AuthorizationCodeSchema, ClientCredentialsSchema, ResourceOwnerPasswordSchema } = require('./lib/config');

class AuthorizationCode extends AuthorizationCodeGrantType {
  constructor(options) {
    const config = Joi.attempt(options, AuthorizationCodeSchema, 'Invalid options provided to simple-oauth2');
    const client = new Client(config);

    super(config, client);
  }
fork icon297
star icon0
watch icon29

+ 5 other calls in file

89
90
91
92
93
94
95
96
97
98
 * @param  {Object}   options.path                   Cookie option for Path setting
 */
const authPlugin = {
    name: 'auth',
    async register(server, options) {
        const pluginOptions = joi.attempt(options, AUTH_PLUGIN_SCHEMA, 'Invalid config for plugin-auth');

        /**
         * Generates a profile for storage in cookie and jwt
         * @method generateProfile
fork icon163
star icon972
watch icon65

+ 3 other calls in file

How does joi.attempt work?

joi.attempt is a method in the joi validation library that is used to validate a value against a schema, and throws an error if the validation fails. When you call joi.attempt, you pass in the value to be validated, as well as a schema to validate it against. The schema is defined using the joi API, which allows you to specify the type, structure, and constraints of the value being validated. If the value passes validation, joi.attempt returns the value unchanged. However, if the value fails validation, joi.attempt throws a ValidationError with a message describing the error and any other relevant details. The error object also includes a details property that provides a detailed list of all the validation errors that occurred. Here's an example of how you might use joi.attempt to validate an object against a schema: javascript Copy code {{{{{{{ const Joi = require('joi'); const schema = Joi.object({ username: Joi.string().required(), password: Joi.string().required(), email: Joi.string().email() }); const user = { username: 'johndoe', password: '12345' }; try { const validatedUser = Joi.attempt(user, schema); console.log('User:', validatedUser); } catch (error) { console.error('Validation error:', error.message); } In this example, we define a schema using the Joi API that requires a username and password property, and optionally allows an email property with a valid email address. We then define an object user that contains a username and password property, but no email property. We then call Joi.attempt with the user object and the schema, which attempts to validate the object against the schema. Since the user object does not include an email property, validation fails and Joi.attempt throws a ValidationError with a message describing the error. The error message would be logged to the console using console.error. If the user object had included a valid email property, Joi.attempt would have returned the user object unchanged, and the validated user object would be logged to the console using console.log.

16
17
18
19
20
21
22
23
24
25
class BackbeatProducer extends EventEmitter {

    constructor(config) {
        super();

        const validConfig = joi.attempt(
            config,
            this.getConfigJoi(),
            'invalid config params'
        );
fork icon18
star icon51
watch icon60

18
19
20
21
22
23
24
25
26
27
logger.debug('contributions: received', message)

// validate data
let data
try {
  data = joi.attempt(message, schema)
} catch (err) {
  logger.error('contributions: invalid message', {
    data: message,
    error: err.message
fork icon167
star icon0
watch icon2

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const Joi = require("joi");

const schema = Joi.object({
  username: Joi.string().required(),
  password: Joi.string().required(),
  email: Joi.string().email(),
});

const user = {
  username: "johndoe",
  password: "12345",
};

try {
  const validatedUser = Joi.attempt(user, schema);
  console.log("User:", validatedUser);
} catch (error) {
  console.error("Validation error:", error.message);
}

In this example, we define a schema using the Joi API that requires a username and password property, and optionally allows an email property with a valid email address. We then define an object user that contains a username and password property, but no email property. We then call Joi.attempt with the user object and the schema, which attempts to validate the object against the schema. Since the user object does not include an email property, validation fails and Joi.attempt throws a ValidationError with a message describing the error. The error message would be logged to the console using console.error. If the user object had included a valid email property, Joi.attempt would have returned the user object unchanged, and the validated user object would be logged to the console using console.log.

92
93
94
95
96
97
98
99
100
101
    circuitBreaker: joi.object().optional(),
    circuitBreakerMetrics: joi.object({
        type: joi.string().required(),
    }).optional(),
});
const validConfig = joi.attempt(config, configJoi,
                                'invalid config params');

const { zookeeper, kafka, topic, groupId, queueProcessor,
        fromOffset, concurrency, fetchMaxBytes,
fork icon18
star icon51
watch icon60

125
126
127
128
129
130
131
132
133
134
    description: desc.description,
    types: types,
    resolveType: (val) =>
      find(map(items, (item, i) => {
        try {
          return Joi.attempt(val, item)
        } catch (e) {}
      }))
  })
}
fork icon9
star icon69
watch icon0

942
943
944
945
946
947
948
949
950
951
952
 *
 * @param {String} method method to be tested
 * @returns {String} method valid method
 */
async function validateESRefreshMethod (method) {
  Joi.attempt(method, Joi.string().label('ES_REFRESH').valid(['true', 'false', 'wait_for']))
  return method
}


/**
fork icon44
star icon17
watch icon25

122
123
124
125
126
127
128
129
130
131
}
const params = getParams(method)
service[name] = async function () {
  const args = Array.prototype.slice.call(arguments)
  const value = _combineObject(params, args)
  const normalized = Joi.attempt(value, method.schema)

  const newArgs = []
  // Joi will normalize values
  // for example string number '1' to 1
fork icon44
star icon17
watch icon25

968
969
970
971
972
973
974
975
976
977
978
 *
 * @param {String} method method to be tested
 * @returns {String} method valid method
 */
async function validateESRefreshMethod(method) {
  Joi.attempt(method, Joi.string().label("ES_REFRESH").valid(["true", "false", "wait_for"]));
  return method;
}


/**
fork icon44
star icon17
watch icon25

+ 5 other calls in file

121
122
123
124
125
126
127
128
129
130
}
const params = getParams(method);
service[name] = async function () {
  const args = Array.prototype.slice.call(arguments);
  const value = _combineObject(params, args);
  const normalized = Joi.attempt(value, method.schema);

  const newArgs = [];
  // Joi will normalize values
  // for example string number '1' to 1
fork icon44
star icon17
watch icon25

37
38
39
40
41
42
43
44
45
46
 * @param {Object} params.mongoConfig.database - metadata database
 * @param {string[]} params.activeExtensions - list of all active extension names
 * @param {Object} params.logger - logger
 */
constructor(params) {
    const validatedParams = joi.attempt(params, paramsJoi);
    Object.assign(params, validatedParams);
    this._config = params.config;
    this._mongoConfig = params.mongoConfig;
    this._activeExtensions = params.activeExtensions;
fork icon18
star icon51
watch icon60

+ 8 other calls in file

167
168
169
170
171
172
173
174
175
176


//attempt
// throws error
// console.log(Joi.attempt('x', Joi.number()));
// const result = Joi.attempt('4', Joi.number());
// console.log(result);

//assert 
// console.log(Joi.assert('1', Joi.number()));
fork icon0
star icon0
watch icon0

150
151
152
153
154
155
156
157
158
- `message` - optional message string prefix added in front of the error message. may also be an Error object.
- `options` - optional options object, passed in to [`any.validate`](#anyvalidatevalue-options)

```js
Joi.attempt('x', Joi.number()); // throws error
const result = Joi.attempt('4', Joi.number()); // result -> 4
```

### `cache.provision([options])`
fork icon0
star icon0
watch icon176

+ 3 other calls in file