Skip to content

Instantly share code, notes, and snippets.

@the-frey
Created November 27, 2020 14:44
Show Gist options
  • Select an option

  • Save the-frey/c9a512bef5ac4031fee8583baa1cf296 to your computer and use it in GitHub Desktop.

Select an option

Save the-frey/c9a512bef5ac4031fee8583baa1cf296 to your computer and use it in GitHub Desktop.
const userExistsHandler = (userExists: boolean): E.Either<t.Error, boolean> => {
if (R.equals(userExists, true)) {
return E.left({
statusCode: 400,
errorType: t.ErrorType.generic,
errorMessage: 'User already exists'
});
} else {
return E.right(true);
}
};
const createPipeline = (eventBody): RTE.ReaderTaskEither<db.System, t.Error, t.Entity> =>
Do(RTE.readerTaskEither)
.bind('userValues', RTE.fromEither(uXfms.userFromCreateRequestE(eventBody)))
.bindL('userAlreadyExists', ({userValues}) => uDb.userExistsRTE(userValues))
.doL(({userAlreadyExists}) => RTE.fromEither(userExistsHandler(userAlreadyExists)))
.do(db.beginTransactionRTE())
.bindL('insertedUserRes', ({userValues}) => uDb.insertUserRTE(userValues))
.bindL('insertedUser', ({insertedUserRes}) => RTE.fromEither(uXfms.getUserFromRes(insertedUserRes)))
.bindL('userResponse', ({insertedUser}) => RTE.fromEither(uXfms.serialiseUserE(insertedUser)))
.return(({userResponse}) => { return { entityType: t.EntityType.user, entity: userResponse };});
const sharedLogic = async (event: requests.MinimalRequestEvent): Promise<responses.Response> => {
const system: db.System = await db.getSystem();
const client = system.pgclient;
try {
const main = (eventBody): RT.ReaderTask<db.System, responses.Response> =>
pipe(
createPipeline(eventBody),
RTE.fold(
errRes => db.leftRightTxnRT(responses.errorToResponse(errRes), db.rollbackRT),
userRes => db.leftRightTxnRT(responses.entityToResponse(userRes), db.commitRT)
));
const response = await main(event.body)(system)();
return response;
} catch (err) {
console.log(err);
return responses.respond500('project/error', 'Something went wrong');
} finally {
await db.closeDbConn(client);
}
};
export const usersCreate = async (event: requests.MinimalRequestEvent): Promise<responses.Response> => {
const userValues = uXfms.createRequestToUser(event.body);
// catch somebody trying to update a user other
// than the logged-in user
const headerUser = uXfms.getUserIdFromHeader(event);
if(!(uDb.valid(headerUser, userValues))) {
return responses.respond400('project/error', 'Authentication error');
}
const response = await sharedLogic(event);
return response;
};
export const proxyUsersCreate = async (event: requests.MinimalRequestEvent): Promise<responses.Response> => {
const response = await sharedLogic(event);
return response;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment