Set custom log level for tests when using Sails.js - sails.js

I'd like to set the log level to ERROR when running unit, integration and acceptance tests. Is it possible to do this while keeping the default setting for the application in config/log.js unchanged?
Sails.js documentation recommends setting the log level to ERROR for tests but doesn't explain how you can do it. Is it possible by setting an environment variable or other means?
Thanks

If you want to set log level to 'error' only in your test you can do it by modifying your test/bootstrap.test.js file.
before(function(done) {
this.timeout(5000);
Sails.lift({
log: {
level: 'error'
}
}, function(err, server) {
sails = server;
if (err) return done(err);
// here you can load fixtures, etc.
done(err, sails);
});
});
By that you can modify every setting from config you want. For example i disabled csrf and 2 hooks i don't use. You can also change connection to database if needed in this place.

Related

How to configure fastify and openapiglue to only coerce query parameters

Our application is using fastify and we're registering the openapiGlue plugin to parse/validate http requests. We're using the ajv option to disable all type coercion.
Everything works great...
However, the issue with the ajv coerce option is that it is applied globally. What we'd like to do is enable type coercion only for the query parameters, but since the ajv coerce option is global, there's no way to do that.
We've tried to register another plugin, that we wrote, after the openapiGlue that uses the fastify setValidatorCompiler() to solve this problem for us. We've set up separate ajv options sections that get applied based on the part of the http request getting validated. The issue is the setValidatorCompiler callback function never gets invoked for any of the message parts, and thus we are unable to enable type coercion on just the query parameters.
It's as if the openapiGlue plugin doesn't want to relinquish control of the message parsing and validating.
Anyone have any suggestions?
// this works
await app.register(openapiGlue, {
specification: localSystemApi,
service: handlers,
prefix: apiPrefix,
ajvOptions: {
coerceTypes: false // defaults to true by openapiGlue otherwise
}
});
// new code to add plugin to only coerce query parameters
// has no effect.
await app.register(ajvPlugin);
// Our ajvPlugin
const httpPartSchema = z.union([z.literal('body'), z.literal('headers'), z.literal('querystring'), z.literal('params')]);
export const ajvPlugin: FastifyPluginAsync<FastifyOpenapiGlueOptions> = async (fastify) => {
fastify.setValidatorCompiler(({ schema, httpPart }) => {
// this code never gets invoked
if (httpPart === undefined) {
throw new Error('Missing httpPart');
}
const parseResult = httpPartSchema.parse(httpPart);
const compiler = schemaCompilers[parseResult];
return compiler.compile(schema) as any;
});
};
The issue is the setValidatorCompiler callback function never gets invoked for any of the message parts, and thus we are unable to enable type coercion on just the query parameters
This is a feature 😄
Fastify does not create any ajv instances if your routes do not use the schema option to speed up your server startup time.
You can do what you need by adding a route that adds a schema.query object.
I would suggest to use the fastify-split-validator plugin to change the ajv settings based on the HTTP entity.
As further reading, this issue in the fastify repository explains in detail how it works.

Working with URL parameters in custom Kibana plugin

I am working on a custom plugin to Kibana (7.5.2). The plugin is of type 'app'. I would like to be able to pass parameters to this plugin in order to pre-load some data from Elasticsearch. I.e., I need to provide users with some specific URLs containing parameters that will be used by the plugin to show only a relevant portion of data.
My problem is that I was not able to find sufficient documentation on this and I do not know what the correct approach should be. I will try to summarize what I know/have done so far:
I have read the official resources on plugin development
I am aware of the fact that _g and _a URL parameters are used to pass state in Kibana applications. However, a) I am not sure if this is the correct approach in my case and b) I also failed to find any information on how my plugin should access the data from these parameters.
I checked the sources of other known plugins, but again, failed to find any clues.
I am able to inject some configuration values using injectUiAppVars in the init method of my plugin (index.js) and retrieve these values in my app (main.js):
index.js:
export default function (kibana) {
return new kibana.Plugin({
require: ['elasticsearch'],
name: ...,
uiExports: {
...
},
...
init(server, options) { // eslint-disable-line no-unused-vars
server.injectUiAppVars('logviewer', async () => {
var kibana_vars = await server.getInjectedUiAppVars('kibana');
var aggregated_vars = { ...kibana_vars, ...{ mycustomparameter: "some value" } }
return aggregated_vars
});
...
}
});
}
main.js
import chrome from 'ui/chrome';
. . .
const mycustomparameter = chrome.getInjected('mycustomparameter');
Providing that I manage to obtain parameters from URL, this would allow me to pass them to my app (via mycustomparameter), but again, I am not sure if this approach is correct.
I tried to get some help via the Elastic forum, but did not receive any answer yet.
My questions
1. Is there any source of information on this particular topic? I am aware of the fact that the plugin API changes frequently, hence I do not expect to find an extensive documentation. Maybe a good example?
Am I completely off course with the way I am trying to achieve it?
Thanks for reading this, any help would be much appreciated!

How RestBase wiki handle caching

Following the installation of RestBase using standard config, I have a working version of summary API.
The problem that the caching mechanism seems strange to me.
The piece of code would decide whether to look at a table cache for fast response. But I cannot make it a server-cache depend on some time-constrain (max-age when the cache is written for example). It means that the decision to use cache or not entirely depend on clients.
Can someone explain the workflow of RestBase caching mechanism?
// Inside key.value.js
getRevision(hyper, req) {
//This one get the header from client request and decide to use cache
or not depend on the value. Does it mean server caching is non-existent?
if (mwUtil.isNoCacheRequest(req)) {
throw new HTTPError({ status: 404 });
}
//If should use cache, below run
const rp = req.params;
const storeReq = {
uri: new URI([rp.domain, 'sys', 'table', rp.bucket, '']),
body: {
table: rp.bucket,
attributes: {
key: rp.key
},
limit: 1
}
};
return hyper.get(storeReq).then(returnRevision(req));
}
Cache invalidation is done by the change propagation service, which is triggered on page edits and similar events. Cache control headers are probably set in the Varnish VCL logic. See here for a full Wikimedia infrastructure diagram - it is outdated but gives you the generic idea of how things are wired together.

Hook for REST validation with sailsjs

I need to create a validation layer for my REST services, I'm using sailsjs.
Someone know how can I do that?
I tried to create a hook but I cant access routes definitions and the hook is called before start policies :'(
The way is something like picture below.
It is perfectly fine to use policies to pre-process requests before they are passed to the controllers. Policies are not just for authentication and acl. They are so versatile you can use them for anything.
E.g.
policies/beforeUpdateTicket.js
module.exports = function(req, res, ok) {
TicketService.checkTicket(req.params.id, null, true).then(function(ticket) {
# You can even modify req.body
req.body.checked = true;
return ok();
}).fail(function(err) {
# Don't go to the controller, respond with error
return res.send(JSON.stringify({
message: 'some_error'
}), 409);
});
};

Not Seeing Id In Sails JS Response

So I'm messing around with SailsJS to try to get an API up and running real fast. I haven't setup a data store yet (will probably use mongodb) but I saw that there is what I'm assuming is like a SQLite database or something. So I generated a model and controller for a User. So in the browser I hit user/create. I see createdAt and updatedAt but no Id. Do I need a real datastore to see an ID? Is this still something you get for free?
Adapter
// Configure installed adapters
// If you define an attribute in your model definition,
// it will override anything from this global config.
module.exports.adapters = {
// If you leave the adapter config unspecified
// in a model definition, 'default' will be used.
'default': 'disk',
// In-memory adapter for DEVELOPMENT ONLY
// (data is NOT preserved when the server shuts down)
memory: {
module: 'sails-dirty',
inMemory: true
},
// Persistent adapter for DEVELOPMENT ONLY
// (data IS preserved when the server shuts down)
// PLEASE NOTE: disk adapter not compatible with node v0.10.0 currently
// because of limitations in node-dirty
// See https://github.com/felixge/node-dirty/issues/34
disk: {
module: 'sails-dirty',
filePath: './.tmp/dirty.db',
inMemory: false
},
// MySQL is the world's most popular relational database.
// Learn more: http://en.wikipedia.org/wiki/MySQL
mysql: {
module : 'sails-mysql',
host : 'YOUR_MYSQL_SERVER_HOSTNAME_OR_IP_ADDRESS',
user : 'YOUR_MYSQL_USER',
password : 'YOUR_MYSQL_PASSWORD',
database : 'YOUR_MYSQL_DB'
}
};
Model
/*---------------------
:: User
-> model
---------------------*/
module.exports = {
attributes: {
firstName: 'STRING',
lastName: 'STRING'
}
};
Do .../user/findAll to list all the users. Each user should have an 'id' property, e.g.
{
"username":"admin",
"password":"$2a$10$SP/hWtlJINkMgkAuAc9bxO1iWsvVcglwEU4ctGCiYpx.7ykaFWt56",
"createdAt":"2013-07-12T17:36:29.852Z",
"updatedAt":"2013-07-12T17:36:29.852Z",
"id":1
}
they removes findAll you can simply use find instad
u can also request like this http://example.de/Model/create?firstname=Foo&lastname=bar
I have checkout this by switching between different DB in a same sails application and its working absolutely fine.
So In this case you can add a property of autoPK to your model and setting it to true like following:
module.exports = {
attribute:{
//your model attributes with validations.
},
autoPK:true
}
If this doesn't works for you then I think there is something wrong with your copy of sails you installed on your system.
Please try to install the newer version (v0.9.8) of sails using npm or try to update your package.json with newer version (v0.9.8) details and excute npm install.