How to access a request level context in the repository #9273
Replies: 1 comment
-
Hey @ralluri-sudo 👋 as far as I know it is not possible to access the request context in Here is an example of a repository mixin which sets metadata properties such as export function MetadataRepositoryMixin<
T extends Entity & WithMetadataProperties,
ID,
Relations extends object = {},
R extends MixinTarget<Repository<T>> = Constructor<DefaultCrudRepository<T, ID, Relations>>
>(repositoryClass: R) {
class MetadataRepository extends repositoryClass {
@inject(AuthenticationBindings.CURRENT_USER, { optional: true })
currentUser: UserDetails = {};
async entityToData<E extends T>(entity: E | DataObject<E>, options?: Options): Promise<E> {
const data = (await super.entityToData(entity, options)) as E;
const username = this.currentUser.username ?? METADATA_DEFAULT_USERNAME;
const now = new Date();
data.createdBy = username;
data.createdAt = now;
data.modifiedBy = username;
data.modifiedAt = now;
return data;
}
definePersistedModel(entityClass: T): juggler.PersistedModelClass {
const modelClass = super.definePersistedModel(
entityClass
) as juggler.PersistedModelClass;
modelClass.observe("before save", async ctx => {
const isNewInstance = ctx.instance != null;
if (!isNewInstance) {
const data = ctx.data as Partial<T>;
delete data.createdBy;
delete data.createdAt;
}
});
return modelClass;
}
}
return MetadataRepository;
} Just as a side note to what you are trying to do, you need to make sure you can trust the request header if you want to use the value from there, if it is set and always overriden by an internal proxy you are probably fine but else you should be cautions as this header can easily be spoofed. I hope that helps, let me know if you have further questions. |
Beta Was this translation helpful? Give feedback.
-
Hey Loopback 4 Community! I am currently trying to access the request level context in the repository. I have been using definePersistedModel in the repository to save a CreatedDate field for a model. I also have a createdBy field that I want to use to store the username located in the requestheaders. Not sure how I can do this, does anyone have any ideas?
Beta Was this translation helpful? Give feedback.
All reactions