109 lines
2.4 KiB
JavaScript
Raw Permalink Normal View History

'use strict';
2020-12-29 17:44:14 +01:00
const { clone, has, concat, isNil } = require('lodash/fp');
const qs = require('qs');
const request = require('supertest');
const { createUtils } = require('./utils');
const createAgent = (strapi, initialState = {}) => {
2020-12-29 17:44:14 +01:00
const state = clone(initialState);
const utils = createUtils(strapi);
2022-08-08 23:33:39 +02:00
const agent = (options) => {
const { method, url, body, formData, qs: queryString, headers } = options;
const supertestAgent = request.agent(strapi.server.httpServer);
2020-12-29 17:44:14 +01:00
if (has('token', state)) {
supertestAgent.auth(state.token, { type: 'bearer' });
}
if (headers) {
supertestAgent.set(headers);
} else if (has('headers', state)) {
supertestAgent.set(state.headers);
}
2020-12-29 17:44:14 +01:00
const fullUrl = concat(state.urlPrefix, url).join('');
2020-12-29 17:44:14 +01:00
const rq = supertestAgent[method.toLowerCase()](fullUrl);
if (queryString) {
rq.query(qs.stringify(queryString));
}
if (body) {
rq.send(body);
}
if (formData) {
2022-08-08 23:33:39 +02:00
const attachFieldToRequest = (field) => rq.field(field, formData[field]);
Object.keys(formData).forEach(attachFieldToRequest);
}
2020-12-29 17:44:14 +01:00
if (isNil(formData)) {
rq.type('application/json');
}
return rq;
};
2022-08-08 23:33:39 +02:00
const createShorthandMethod =
(method) =>
(url, options = {}) => {
return agent({ ...options, url, method });
};
2020-12-29 17:44:14 +01:00
Object.assign(agent, {
assignState(newState) {
Object.assign(state, newState);
return agent;
},
setURLPrefix(path) {
return this.assignState({ urlPrefix: path });
},
setToken(token) {
return this.assignState({ token });
},
setLoggedUser(loggedUser) {
return this.assignState({ loggedUser });
},
setHeaders(headers) {
return this.assignState({ headers });
},
getLoggedUser() {
2020-12-29 17:44:14 +01:00
return state.loggedUser;
},
async login(userInfo) {
2020-12-29 17:44:14 +01:00
const { token, user } = await utils.login(userInfo);
this.setToken(token).setLoggedUser(user);
2020-12-29 17:44:14 +01:00
return agent;
},
async registerOrLogin(userCredentials) {
2020-12-29 17:44:14 +01:00
const { token, user } = await utils.registerOrLogin(userCredentials);
this.setToken(token).setLoggedUser(user);
2020-12-29 17:44:14 +01:00
return agent;
},
get: createShorthandMethod('GET'),
post: createShorthandMethod('POST'),
put: createShorthandMethod('PUT'),
delete: createShorthandMethod('DELETE'),
});
2020-12-29 17:44:14 +01:00
return agent;
};
module.exports = {
createAgent,
};